199-Binary Tree Right Side View
Description
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, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
問題描述
給定二叉樹, 返回以從右邊看的視角所能獲取到的值。
問題分析
BFS或者DFS
DFS使用前序遍歷(與一般的前序遍歷的不同的地方為先從右邊遍歷), 另外注意利用height
解法1
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
// reverse level traversal
List<Integer> result = new ArrayList();
if(root == null) return result;
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
while (queue.size() != 0) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
if (i == 0) result.add(cur.val);
if (cur.right != null) queue.offer(cur.right);
if (cur.left != null) queue.offer(cur.left);
}
}
return result;
}
}
解法2
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList();
if(root == null) return res;
preorder(root, res, 0);
return res;
}
public void preorder(TreeNode root, List<Integer> res, int height){
if(root == null) return;
if(height == res.size()) res.add(root.val);
preorder(root.right, res, height + 1);
preorder(root.left, res, height + 1);
}
}
相關文章
- LeetCode-Binary Tree Right Side ViewLeetCodeIDEView
- odoo form view套treeOdooORMView
- WPF live visual tree Right click,show properties,DataContextContext
- Leetcode-Populating Next Right Pointer in Binary Tree IILeetCode
- 使用postgresql作為 bootstrap tree view 後端SQLbootView後端
- Tree View控制元件(新增,移除,設定圖示)View控制元件
- By My SideIDE
- Client Side Cache 和 Server Side Cache 的區別clientIDEServer
- Failover 之 Client-Side Connect time Failover、Client-Side TAF、Service-Side TAFAIclientIDE
- clear:left/right 理解
- XPages 開發實踐:開發通用的 Tree View 定製控制元件View控制元件
- BUUCTF:Beautiful_SideIDE
- Swift Server-sideSwiftServerIDE
- Service-side TAFIDE
- umask side-effectIDE
- hadoop 多表join:Map side join及Reduce side join範例HadoopIDE
- 【譯】 Types are moving to the right
- Oracle Left join right jionOracle
- Right here waitingAI
- Hybris做增強的兩種方式:In App Extension和Side by Side ExtensionAPPIDE
- 【kingsql分享】企業中的Mr.Right Now和Mr.RightSQL
- Goroutines: the dark side of the runtimeGoIDE
- 子元素超過父元素padding-right和margin-right失效padding
- CSS樣式中的right屬性和margin-right屬性的區別CSS
- Tree
- Datatable Scroller (Server Side) Part:3ServerIDE
- Server-side vulnerabilities :path traversalServerIDE
- MySQL LEFT JOIN/ INNER JOIN/RIGHT JOINMySql
- rac 的Client-side TAF配置clientIDE
- replication 1064 error on slave sideErrorIDE
- Rebuild TreeRebuild
- 01 Tree
- DSU on Tree
- 為什麼margin-right不生效
- sql中的join、left join、right joinSQL
- sql left join 和 right join解釋SQL
- 【MySQL(1)| B-tree和B+tree】MySql
- 第10講:Flink Side OutPut 分流IDE