Created
June 11, 2015 07:26
-
-
Save codetalks-new/d1f5ecdea5d3656ce14e to your computer and use it in GitHub Desktop.
Java solution of https://leetcode.com/problems/binary-tree-right-side-view/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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<Integer> rightSideView(TreeNode root) { | |
List<Integer> arr = new ArrayList<Integer>(); | |
if(root == null){ | |
return arr; | |
} | |
List<TreeNode> oneLevel = new ArrayList<TreeNode>(); | |
List<TreeNode> nextLevel = new ArrayList<TreeNode>(); | |
oneLevel.add(root); | |
arr.add(root.val); | |
while(!oneLevel.isEmpty()){ | |
TreeNode current = oneLevel.remove(0) ; | |
if(current.left != null){ | |
nextLevel.add(current.left); | |
} | |
if(current.right != null){ | |
nextLevel.add(current.right); | |
} | |
if(oneLevel.isEmpty()){ | |
if(!nextLevel.isEmpty()){ | |
TreeNode last = nextLevel.get(nextLevel.size() - 1); | |
arr.add(last.val); | |
oneLevel = nextLevel; | |
nextLevel = new ArrayList<TreeNode>(); | |
} | |
} | |
} | |
return arr; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment