1. Title
Binary Tree Right Side View
2. Http address
https://leetcode.com/problems/binary-tree-right-side-view/
3. The question
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <--- / 2 3 <--- 5 4 <---
You should return [1, 3, 4]
.
4. My code(AC)
1 2 public static void getRightSide(TreeNode root, List<Integer> res, boolean depth[],int de){ 3 4 if( root == null) 5 return; 6 if( root.right != null) 7 { 8 if( depth[de] == false) 9 { 10 res.add(root.right.val); 11 depth[de] = true; 12 } 13 getRightSide(root.right, res, depth, de +1); 14 }else{ 15 if( root.left != null && depth[de] == false) 16 { 17 res.add(root.left.val); 18 depth[de] = true; 19 } 20 } 21 22 getRightSide(root.left, res, depth, de +1); 23 } 24 // Accepted 25 public static List<Integer> rightSideView(TreeNode root) { 26 27 List<Integer> res = new ArrayList<Integer>(); 28 boolean depth[] = new boolean[256]; 29 if ( root == null) 30 return res; 31 res.add(root.val); 32 getRightSide(root, res,depth, 1); 33 return res; 34 }