Monday, November 2, 2015

[leetcode]Binary Tree Right Side View

Build on top of the problem "Binary Tree Level Order Traversal II" without reversing the result, and only use the last element of each list

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        levelOrderBottom(root);
        List<Integer> list = new ArrayList<Integer>();
        for(int i = 0; i < result.size(); i++){
            List<Integer> temp = result.get(i);
            list.add(temp.get(temp.size()-1));
        }
        return list;
    }
    
    
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    public void levelOrderBottom(TreeNode root) {
        dfsLevel(root, 0);
    }

    private void dfsLevel(TreeNode root, int level){
     if (root == null) return;
     if (result.size() < level+1) result.add(new ArrayList<Integer>());
     result.get(level).add(root.val);
     dfsLevel(root.left, level+1);
     dfsLevel(root.right, level+1);
    }
    
}

No comments:

Post a Comment