LeetCode 199 Binary Tree Right Side View
来源:互联网 发布:税务数据共享 编辑:程序博客网 时间:2024/06/11 11:16
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]
.
思路,左右子树的高度,两边一直比较,当前高度更高的,就是从右侧可以看到的。同等高度下,优先看到右子树的。
public List<Integer> rightSideView(TreeNode root) {List<Integer> results = new ArrayList<>();if (root != null) helper(root, 1, 0, results);return results;}private int helper(TreeNode root, int cur, int max, List<Integer> results) {if (cur > max) {results.add(root.val);max = cur;}if (root.right != null) max = helper(root.right, cur + 1, max, results);//如果右子树当前节点更高,更新maxif (root.left != null) max = helper(root.left, cur + 1, max, results);//如果左子树,当前节点更高,更新maxreturn max;}
方法二:
public List<Integer> rightSideView(TreeNode root) {List<Integer> result = new ArrayList<Integer>();if (root == null) return result;result.add(root.val);List<Integer> rsvl = rightSideView(root.left);List<Integer> rsvr = rightSideView(root.right);result.addAll(rsvr);if (rsvl.size() > rsvr.size()) {for (int i = rsvr.size(); i < rsvl.size(); i++)result.add(rsvl.get(i));}return result;}
方法三
List<Integer> ans = new ArrayList<>(); Deque<TreeNode> q = new ArrayDeque<>(); if (root!=null) { q.addLast(root); } int curSize = 1, nextSize = 0; for (curSize=1; !q.isEmpty(); curSize=nextSize, nextSize=0) { for (int i=0; i<curSize; ++i) { // there are curSize nodes of current level to be dequeued TreeNode head = q.removeFirst(); if (i == curSize-1) { ans.add(head.val); } // add the value of the last node of current level to answer list if (head.left != null) { q.addLast(head.left); ++nextSize; } if (head.right != null) { q.addLast(head.right); ++nextSize; } } } return ans;
0 0
- [leetcode] 199 Binary Tree Right Side View
- leetcode-199 Binary Tree Right Side View
- 199Binary Tree Right Side View-LeetCode
- [LeetCode 199]Binary Tree Right Side View
- Leetcode 199: Binary Tree Right Side View
- LeetCode 199-Binary Tree Right Side View
- Binary Tree Right Side View - LeetCode 199
- leetcode[199]:Binary Tree Right Side View
- 【Leetcode】Binary Tree Right Side View #199
- LeetCode(199)Binary Tree Right Side View
- [LeetCode 199] Binary Tree Right Side View
- leetcode 199: Binary Tree Right Side View
- 【LEETCODE】199-Binary Tree Right Side View
- Leetcode #199 Binary Tree Right Side View
- LeetCode 199 Binary Tree Right Side View
- [leetcode 199] Binary Tree Right Side View
- leetcode 199 Binary Tree Right Side View
- LeetCode-199:Binary Tree Right Side View
- 283. Move Zeroes
- linux内存中buffer和 cached的比较
- BZOJ1858 [Scoi2010]序列操作
- QPainter
- RISC与CISC
- LeetCode 199 Binary Tree Right Side View
- 斐波那契数列
- 反射机制
- bash的通配符
- WAS的VGC参数
- CentOS下载百度网盘文件的方法
- C#中的自定义控件
- TLS thread local storing
- 情景再现,从源码角度分析异常:The specified child already has a parent