[JAVA]LeetCode199 Binary Tree Right Side View

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<— / \ 23<— \\ 54<— You should return [1, 3, 4]. 题目的含义是:从右边看,,我们能看到的节点有哪些,相当于几何中投影的概念。 解题思路:1)深度遍历,先记录右边节点的最大高度。只有大于最大高度的节点才能打印出来。(我们自己思维去判断的时候,应该更倾向这种逻辑) 2)层次遍历,将最右边的节点存入list表中。这种想法写程序更容易理解。 实现1)思路代码如下所示:

rightSideView(TreeNode root) {TreeNode>();TreeNodeArrayList();TreeNode current=root;int curHeight=1;int rightHeight=0;isEmpty()){if(current!=null){if(curHeight>rightHeight){list.add(current.val);}stack.push(current);stack1.push(current);current=current.right;++curHeight;}else{currentpop();//计算当前current节点所在的height值while(!stack1.isEmpty()){if(stack1.peek()==current){curHeight=stack1.size();if(curHeight>rightHeight)rightHeight=curHeight;break;}stack1.pop();}current=current.left;++curHeight;}}return list;}

实现2)思路程序如下:

rightSideView(TreeNode root) {ArrayList();;LinkedList<TreeNode>();TreeNode current=root;queue.offer(current);(isEmpty()){currentpoll();if(current!=null){){list.add(current.val);}add(current.left);add(current.right);}else{if(queue.isEmpty()){break;}else{queue.add(null);}}}return list;}

大多数人想要改造这个世界,但却罕有人想改造自己。

[JAVA]LeetCode199 Binary Tree Right Side View

相关文章:

你感兴趣的文章:

标签云: