Binary Tree Level Order Traversal2

来源:互联网 发布:乌鲁木齐打车软件 编辑:程序博客网 时间:2024/06/06 00:07
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,#,#,15,7},
    3
   / \
  9 20
    / \
   15 7
return its bottom-up level order traversal as:
[
  [15,7],
  [9,20],
  [3]
]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        
    }
}

分析:
给你一个二叉树,返回它的从底向上的节点值排序,(从左到右,从叶子到根)


public class BinaryTreeLevelOrderTraversal2{    public class TreeNode{        int val;        TreeNode left;        TreeNode right;        TreeNode(int x){val=x;}}    public List<List<Integer>>levelOrderBottom (TreeNode root){}    public bfs(){        }}



相对于该问题的版本1,其就是把结果反着输出
返回结果前加一句:

Collections.reverse(result); 

即可。


答案:

    public List<List<Integer>> levelOrder(TreeNode root) {    List<List<Integer>> result= new ArrayList<List<Integer>>();    if(root==null) return result;    Queue<TreeNode> queue = new LinkedList<TreeNode>();         queue.add(root);    int curLevelCount=1;    int nextLevelCount=0;    while(!queue.isEmpty()){    ArrayList<Integer> level = new ArrayList<Integer>();    while(curLevelCount>0){    TreeNode temp = queue.remove();    curLevelCount--;    if(temp.left!=null) {nextLevelCount++; queue.add(temp.left);}    if(temp.right!=null) {nextLevelCount++; queue.add(temp.right);}    level.add(temp.val);    }    curLevelCount=nextLevelCount;    nextLevelCount=0;    result.add(level);        }    Collections.reverse(result);    return result;    }


0 0
原创粉丝点击