2015年4月23日星期四

Binary Tree Level Order Traversal II leetcode

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]
]
跟之前题一样, 只是每次添加时候都添加到0位置.做这道题范2了把for循环里的treenode 又起名为root 搞得出错了
第二种方法想法比较简单 但是要声明两次level的组
时间O(n) 空间O(n)

public class Solution {
    public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if (root == null){
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()){
            ArrayList<Integer> level = new ArrayList<Integer>();
            int size = queue.size();
            for (int i = 0; i < size; i++){
                TreeNode cur = queue.poll();
                level.add(cur.val);
                if (cur.left != null){
                    queue.offer(cur.left);
                }
                if (cur.right != null){
                    queue.offer(cur.right);
                }
            }
            result.add(0, level);
        }
        return result;
    }
}


public class Solution {
    public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if (root == null){
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int curlevel = 1;
        int nextlevel = 0;
        ArrayList<Integer> level = new ArrayList<Integer>();
        while (!queue.isEmpty()){
            
            TreeNode cur = queue.poll();
            level.add(cur.val);
            curlevel--;
            if (cur.left != null){
                queue.offer(cur.left);
                nextlevel++;
            }
            if (cur.right != null){
                queue.offer(cur.right);
                nextlevel++;
            }
            if (curlevel == 0){
                curlevel = nextlevel;
                nextlevel = 0;
                result.add(0, level);
                level = new ArrayList<Integer>();
            }
        }
        return result;
    }
}

没有评论:

发表评论