码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 107. Binary Tree Level Order Traversal II

时间:2020-01-05 10:02:41      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:==   class   efi   rac   amp   integer   solution   from   dep   

Given a binary tree, return the bottom-up level order traversal of its nodes‘ values. (ie, from left to right, level by level from leaf to root).

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

    3
   /   9  20
    /     15   7

 

return its bottom-up level order traversal as:

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

Solution 1:
BFS
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> arrList = new ArrayList<>();
        if (root == null) {
            return arrList;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                list.add(cur.val);
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            arrList.add(0, list);
        }
        return arrList;
    }
}

 

Solution 2:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> arrList = new ArrayList<>();
        helper(arrList, 0, root);
        return arrList;
    }
    
    private void helper(List<List<Integer>> res, int depth, TreeNode root) {
        if (root == null) {
            return;
        }
        // backtrack case, resSize >= depth
        if (depth >= res.size()) {
            res.add(0, new LinkedList<>());
        }
        res.get(res.size() - 1 - depth).add(root.val);
        helper(res, depth + 1, root.left);
        helper(res, depth + 1, root.right);
    }
}

[LC] 107. Binary Tree Level Order Traversal II

标签:==   class   efi   rac   amp   integer   solution   from   dep   

原文地址:https://www.cnblogs.com/xuanlu/p/12151471.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!