摘要:问题解答核心思想是每一层只取一个结点,所以的大小与高度是一样的。
问题:
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].
解答:
核心思想是每一层只取一个结点,所以result的大小与高度是一样的。
public class Solution { public void Helper(TreeNode root, Listresult, int curLength) { if (root == null) return; if (curLength == result.size()) { result.add(root.val); } Helper(root.right, result, curLength + 1); Helper(root.left, result, curLength + 1); } public List rightSideView(TreeNode root) { List result = new ArrayList (); Helper(root, result, 0); return result; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/64882.html
Problem 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. Example: Input: [1,2,3,null,5,null,4] Output: [1,...
摘要:代码层序遍历复杂度时间空间对于二叉树思路我们同样可以借用层序遍历的思路,只要每次把这一层的最后一个元素取出来就行了,具体代码参见中的 Binary Tree Right Side View Given a binary tree, imagine yourself standing on the right side of it, return the values of the n...
摘要:有效三角形的个数双指针最暴力的方法应该是三重循环枚举三个数字。总结本题和三数之和很像,都是三个数加和为某一个值。所以我们可以使用归并排序来解决这个问题。注意因为归并排序需要递归,所以空间复杂度为 ...
Problem Given a root of Binary Search Tree with unique value for each node. Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You sho...
阅读 1684·2021-11-18 10:02
阅读 2184·2021-11-15 11:38
阅读 2650·2019-08-30 15:52
阅读 2158·2019-08-29 14:04
阅读 3208·2019-08-29 12:29
阅读 2064·2019-08-26 11:44
阅读 957·2019-08-26 10:28
阅读 802·2019-08-23 18:37