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].
The meaning of the title is: from the right side, we can see what the nodes are, equivalent to the concept of projection in the geometry.
Problem-Solving ideas: 1) Depth traversal, first record the maximum height of the right node. Only nodes larger than the maximum height can be printed. (We should be more inclined to this logic when we think ourselves to judge.)
2) Hierarchy traversal, the rightmost node is stored in the list table. This idea of writing a program is easier to understand.
Implementation 1) The idea code is as follows:
Public List<Integer>Rightsideview (TreeNode root) {Stack<TreeNode> Stack=New Stack<TreeNode>();Stack<TreeNode>Stack1=New Stack<TreeNode>();//Store all nodes to compute the height of the node List<Integer> List=NewArrayList<Integer>(); TreeNode Current=Root int Curheight=1; int Rightheight=0; while(Current!=NULL||!Stack.IsEmpty ()) {if(Current!=NULL) {if(Curheight>Rightheight) {List.Add (current.Val); }Stack.push (current); Stack1.push (current); Current=Current.Right++Curheight; }Else{Current=Stack.Pop ();//Calculates the height value of the current node while(!Stack1.IsEmpty ()) {if(Stack1.Peek ()==Current) {Curheight=Stack1.Size ();if(Curheight>Rightheight) Rightheight=Curheight; Break } stack1.Pop (); } current=Current.Left++Curheight; } }return List; }
Implementation 2) The idea program is as follows:
Public List<Integer>Rightsideview (TreeNode root) {List<Integer> List=NewArrayList<Integer>();if(Root==NULL)return List;Queue<TreeNode> Queue=NewLinkedList<TreeNode>(); TreeNode Current=RootQueue.Offer (current);Queue.OfferNULL);//equivalent to using NULL as a spacer for each layer of nodes while(!Queue.IsEmpty ()) {current=Queue.Poll ();if(Current!=NULL) {if(Queue.Peek ()==NULL) {List.Add (current.Val); }if(Current.Left!=NULL)Queue.Add (current.left);if(Current.Right!=NULL)Queue.Add (current.right); }Else{if(Queue.IsEmpty ()) {break; }Else{Queue.AddNULL); } } }return List; }
[JAVA] LeetCode199 Binary Tree Right Side View