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);
}
}
相關文章
- WPF live visual tree Right click,show properties,DataContextContext
- odoo form view套treeOdooORMView
- Tree View控制元件(新增,移除,設定圖示)View控制元件
- Client Side Cache 和 Server Side Cache 的區別clientIDEServer
- 【譯】 Types are moving to the right
- Goroutines: the dark side of the runtimeGoIDE
- Swift Server-sideSwiftServerIDE
- BUUCTF:Beautiful_SideIDE
- 音影片領域中, 5.1 7.1聲道不同版本的區別 ---- 5.1 5.1(side) 7.1 7.1(side) 7.1(wide-side)IDE
- Hybris做增強的兩種方式:In App Extension和Side by Side ExtensionAPPIDE
- border-right製作的
- Datatable Scroller (Server Side) Part:3ServerIDE
- Server-side vulnerabilities :path traversalServerIDE
- MySQL LEFT JOIN/ INNER JOIN/RIGHT JOINMySql
- 116-Populating Next Right Pointers in Each Node
- 第10講:Flink Side OutPut 分流IDE
- tree
- 想列印k8s資源YAML結果搞懂了Client-Side & Server-Side ApplyK8SYAMLclientIDEServerAPP
- 117. Populating Next Right Pointers in Each Node II
- CSS @page:right列印偽類選擇器CSS
- 117-Populating Next Right Pointers in Each Node II
- [20230508]ORA-00907 missing right parenthesis.txt
- Sql 中的 left 函式、right 函式SQL函式
- Android自定義View:View(二)AndroidView
- ViewView
- Android View 系統 1 - View樹AndroidView
- SAP S/4HANA Cloud 上 in-app 和 side-by-side 兩種擴充套件方式的介紹CloudAPPIDE套件
- Decision Tree
- Tree Compass
- A - Distance in Tree
- DSU on Tree
- Rebuild TreeRebuild
- 01 Tree
- Leetcode 117. Populating Next Right Pointers in Each Node IILeetCode
- [LeetCode] 2516. Take K of Each Character From Left and RightLeetCode
- mysql常用連線查詢join,left,right,crossMySqlROS
- server-side-events(SSE)開發指南(Node)ServerIDE
- SIDE上海配音工作室完成擴建IDE