文章目录
  1. 1. Binary Tree Right Side View
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题

Binary Tree Right Side View

题目

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].

思路

层次遍历

解题

c++版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> result;
levelOrder(root,1,result);
return result;
}


void levelOrder(TreeNode* root,int level,vector<int>& result){
if(!root)
return;
if(level>result.size())
result.push_back(0);
result[level-1]=root->val;
levelOrder(root->left,level+1,result);
levelOrder(root->right,level+1,result);
}

};

Python版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
# @param {TreeNode} root
# @return {integer[]}
def rightSideView(self, root):
result=[]
self.levelOrder(root,1,result)
return result

def levelOrder(self,root,level,result):
if not root:
return
if level>len(result):
result.append(0)
result[level-1]=root.val
self.levelOrder(root.left,level+1,result)
self.levelOrder(root.right,level+1,result)

文章目录
  1. 1. Binary Tree Right Side View
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题