102-Binary Tree Level Order Traversal

kevin聰發表於2018-05-06

Description

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).


For example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

問題描述

給定二叉樹, 返回其層級遍歷的值


問題分析


解法1(BFS)

public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> wrapList = new LinkedList();
        if(root == null) return wrapList;

        Queue<TreeNode> queue = new LinkedList();
        queue.offer(root);
        while(!queue.isEmpty()){
            int levelNum = queue.size();
            List<Integer> subList = new LinkedList();
            for(int i = 0; i < levelNum; i++) {
                if(queue.peek().left != null)   queue.offer(queue.peek().left);
                if(queue.peek().right != null)  queue.offer(queue.peek().right);
                subList.add(queue.poll().val);
            }
            wrapList.add(subList);
        }

        return wrapList;
    }
}

解法2(DFS)

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList();
        levelTraverse(root, 0, res);
        return res;
    }
    private void levelTraverse(TreeNode root, int depth, List<List<Integer>> res) {
        if(root == null)    return;

        if(res.size() == depth) res.add(new ArrayList());
        res.get(depth).add(root.val);
        levelTraverse(root.left, depth + 1, res);
        levelTraverse(root.right, depth + 1, res);
    }
}

相關文章