摘要:問題解答核心思想是每一層只取一個結點,所以的大小與高度是一樣的。
問題:
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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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...
閱讀 1702·2021-11-18 10:02
閱讀 2218·2021-11-15 11:38
閱讀 2666·2019-08-30 15:52
閱讀 2190·2019-08-29 14:04
閱讀 3231·2019-08-29 12:29
閱讀 2086·2019-08-26 11:44
閱讀 994·2019-08-26 10:28
閱讀 830·2019-08-23 18:37