# leetcode 199. Binary Tree Right Side View-树的右视图|递归|非递归|Java|Python

原题链接：199. Binary Tree Right Side View

【思路】非递归实现

public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) return res;
while (!queue.isEmpty()) {
int n = queue.size();
while(n-- > 0) {
root = queue.poll();
}
}
return res;
}
}
210 / 210 test cases passed. Runtime: 2 ms  Your runtime beats 47.48% of javasubmissions.

import Queue
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None : return []
queue, res = Queue.Queue(),[]
queue.put(root)
while not queue.empty() :
n = queue.qsize()
while (n > 0) :
root = queue.get()
if root.left : queue.put(root.left)
if root.right : queue.put(root.right)
if n == 1 : res.append(root.val)
n -= 1
return res
210 / 210 test cases passed. Runtime: 68 ms  Your runtime beats 15.41% of pythonsubmissions.

【思路】递归实现

public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
dfs(root, res, 0);
return res;
}
private void dfs(TreeNode root, List<Integer> res, int level) {
if (root == null) return;
if (level == res.size()) {
}
dfs(root.right, res, level+1);
dfs(root.left, res, level+1);
}
}
210 / 210 test cases passed. Runtime: 1 ms  Your runtime beats 84.55% of javasubmissions.

• 本文已收录于以下专栏：

举报原因： 您举报文章：leetcode 199. Binary Tree Right Side View-树的右视图|递归|非递归|Java|Python 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)