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;
    }
}

喜欢的话订阅一个呗~第一时间收到文章更新哟~

发表评论

电子邮件地址不会被公开。