给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4] 输出: [1, 3, 4] 解释: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
C++
/**
* 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:
void dfs(TreeNode* root, map<int,int>& tmp, int num)
{
if(root)
{
tmp[num]=root->val;
dfs(root->left,tmp,num+1);
dfs(root->right,tmp,num+1);
}
}
vector<int> rightSideView(TreeNode* root)
{
map<int,int> tmp;
dfs(root,tmp,0);
vector<int> res;
for(auto it:tmp)
{
res.push_back(it.second);
}
return res;
}
};
python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def dfs(self,root,dic,num):
if root:
dic[num]=root.val
self.dfs(root.left,dic,num+1)
self.dfs(root.right,dic,num+1)
def rightSideView(self, root: TreeNode) -> List[int]:
dic={}
self.dfs(root,dic,0)
res=[]
for key in dic:
res.append(dic[key])
return res