1 //My Code2 PackageLeetcode;3 /**4 * 199. Binary Tree right Side View5 * Address:https://leetcode.com/problems/binary-tree-right-side-view/6 * Given A binary tree, imagine yourself standing on the right side of it,7 * Return the values of the nodes you can see ordered from top to bottom.8 * 9 */Ten ImportJava.util.*; One A Public classBinarytreerightsideview { - Public Static voidMain (string[] args) { -Treenode[] Tree =NewTreenode[9]; the for(inti = 1; I < 9; i++){ -Tree[i] =NewTreeNode (i); - } -Treenode.link (tree, 1, 2, 3); +Treenode.link (Tree, 2, 4, 5); -Treenode.link (Tree, 3, 6, 1); +Treenode.link (Tree, 5, 7, 8); A //First Order Traversal atTreenode.preprint (tree[1]); - //Solution -list<integer> result = Rightsideview (tree[1]); - System.out.println (result); - - //Solution2 inlist<integer> result2 = RightSideView2 (tree[1]); - System.out.println (RESULT2); to + } - /** the * Method One: Time complexity is high, need O (n), n is the number of nodes in the tree * * @paramRoot $ * @returnPanax Notoginseng */ - Public StaticList<integer>Rightsideview (TreeNode root) { thelist<integer> result =NewArraylist<>(); +queue<treenode> queue =NewLinkedlist<>(); A intChildnum = 0; the if(Root! =NULL){ + Queue.offer (root); - while(!Queue.isempty ()) { $TreeNode node =Queue.poll (); $ if(node.left!=NULL){ - Queue.offer (node.left); -childnum++; the } - if(Node.right! =NULL)Wuyi { the Queue.offer (node.right); -childnum++; Wu } -System.out.println ("queue.size () =" +queue.size ()); About if(childnum-queue.size () = = 0){ $ Result.add (node.val); -Childnum = 0; - } - } A } + the returnresult; - $}
1 /**2 * Method Two3 * The solution of others ' home, ingenious, fast and good understanding4 * @paramRoot5 * Right-to-left depth takes precedence over, saving the first node of each layer. Use the size of the current result table as the identity, so that each node that is saved is the first node that appears at that layer6 * @return7 */8 Public StaticList<integer>rightSideView2 (TreeNode root) {9list<integer> res =NewArraylist<integer>();Ten if(Root = =NULL){ One returnRes; A } -DFS (root, res, 0); - returnRes; the } - - Public Static voidDFS (TreeNode root, list<integer> res,intLevel ) { - if(Root = =NULL){ + return; - } + if(res.size () = =Level ) { A Res.add (root.val); at } - if(Root.right! =NULL){ -DFS (Root.right, res, level + 1); - } - if(Root.left! =NULL){ -DFS (Root.left, res, level + 1); in } -}
Leetcode 199:binary Tree Right Side View