102. Binary Tree Level Order Traversal

Posted optor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了102. Binary Tree Level Order Traversal相关的知识,希望对你有一定的参考价值。

原题链接:https://leetcode.com/problems/binary-tree-level-order-traversal/description/
这道题目级别为“Easy”,解答出来也确实容易!直接使用个队列进行递归即可:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);

        TreeNode rootLeft = new TreeNode(2);
        TreeNode rootRight = new TreeNode(3);
        root.left = rootLeft;
        root.right = rootRight;

        TreeNode leftLeft = new TreeNode(3);
        TreeNode leftRight = null;
        rootLeft.left = leftLeft;
        rootLeft.right = leftRight;

        TreeNode rightLeft = new TreeNode(2);
        TreeNode rightRight = null;
        rootRight.left = rightLeft;
        rootRight.right = rightRight;

        Solution s = new Solution();
        System.out.println(s.levelOrder(root));
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        dfs(queue, res);
        return res;
    }

    public void dfs(Queue<TreeNode> parentQueue, List<List<Integer>> res) {
        Queue<TreeNode> childQueue = new LinkedList<>();

        List<Integer> parentVals = new ArrayList<>();
        while (!parentQueue.isEmpty()) {
            TreeNode node = parentQueue.poll();
            parentVals.add(node.val);

            if (node.left != null) {
                childQueue.add(node.left);
            }
            if (node.right != null) {
                childQueue.add(node.right);
            }
        }
        res.add(parentVals);
        if (childQueue.size() > 0) {
            dfs(childQueue, res);
        }
    }
}

以上是关于102. Binary Tree Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章

102. Binary Tree Level Order Traversal

LeetCode102. Binary Tree Level Order Traversal

102Binary Tree Level Order Traversal

102. Binary Tree Level Order Traversal

Leetcode 102. Binary Tree Level Order Traversal

[LeetCode]题解(python):102 Binary Tree Level Order Traversal