您的位置 首页 JAVA(2017)

107. Binary Tree Level Order Traversal II

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

/**
 * 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) {
        
        Queue<TreeNode> nodes = new LinkedList<TreeNode>();
        List<List<Integer>> res = new LinkedList();
        if(root == null) return res;
        nodes.add(root);
        while(!nodes.isEmpty()){
            List<Integer> sub = new LinkedList();
            int num = nodes.size();
            for(int i=0;i<num;i++){
                TreeNode curr = nodes.poll();
                sub.add(curr.val);
                if(curr.left != null) nodes.add(curr.left);
                if(curr.right != null) nodes.add(curr.right);
            }
            res.add(0,sub);
            
        }
        return res;
    }
}
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《107. Binary Tree Level Order Traversal II》

发表评论

邮箱地址不会被公开。

返回顶部