Binary Tree Level Order Traversal II

来源:互联网 发布:有限元分析软件msc 编辑:程序博客网 时间:2024/05/22 01:05
<p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">Given a binary tree, return the <span style="box-sizing: border-box;">bottom-up level order</span> traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">For example:<br style="box-sizing: border-box;" />Given binary tree <code style="box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13px; padding: 2px 4px; color: rgb(199, 37, 78); background-color: rgb(249, 242, 244); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px;">{3,9,20,#,#,15,7}</code>,<br style="box-sizing: border-box;" /></p><pre style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13px; padding: 9.5px; margin-top: 0px; margin-bottom: 10px; line-height: 1.42857143; color: rgb(51, 51, 51); word-break: break-all; word-wrap: break-word; background-color: rgb(245, 245, 245); border: 1px solid rgb(204, 204, 204); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px;">    3   / \  9  20    /  \   15   7

return its bottom-up level order traversal as:

[  [15,7],  [9,20],  [3]]
思路: 采用与Binary Tree Level Order Traversal一样的方式,得到结果后将结果逆序集合。 
/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<List<Integer>> levelOrderBottom(TreeNode root) {                 List<List<Integer>> res=new ArrayList<List<Integer>>();        if(root==null) return res;        List<TreeNode> last=new ArrayList<TreeNode>();        last.add(root);        while(!last.isEmpty())        {            List<Integer> cur=new ArrayList<Integer>();            List<TreeNode> cur_Deque=new ArrayList<TreeNode>();            for(TreeNode node: last)            {                cur.add(node.val);            }            for(TreeNode node: last){                if(node.left!=null ) {                    cur_Deque.add(node.left);                }                if(node.right!=null){                    cur_Deque.add(node.right);                }             }            last=new ArrayList<TreeNode>(cur_Deque);            res.add(cur);        }        Collections.reverse(res);        return res;           }  }

0 0