102. Binary Tree Level Order Traversal

yPhantom 2019年10月30日 25次浏览

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]
]

Solution

将树按照层级遍历的方式,返回一个数组。

DFS 递归版

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(root, res, 0);
        return res;
    }
    
    private void dfs(TreeNode root, List<List<Integer>> res, int height) {
        if (root == null) {
            return;
        }
        if (height >= res.size()) {
            res.add(new LinkedList<Integer>());
        }
        res.get(height).add(root.val);
        dfs(root.left, res, height + 1);
        dfs(root.right, res, height + 1);
    }
}

队列

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        queue.offer(root);
        while (!queue.isEmpty()) {
            int height = queue.size();
            List<Integer> tmp = new ArrayList<>();
            for (int i = 0; i < height; i++) {
                TreeNode node = queue.peek();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                tmp.add(queue.poll().val);
            }
            res.add(tmp);
        }
        return res;
    }
}

Python3

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        res = []
        self.dfs(root, res, 0)
        return res
    
    def dfs(self, root, res, height):
        if root is None:
            return
        if height >= len(res):
            res.append([])
        res[height].append(root.val)
        self.dfs(root.left, res, height + 1)
        self.dfs(root.right, res, height + 1)