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


解法:

     对于树的问题,最常见的就是利用递归,因此这题也利用递归实现。我们从上图可以简单的知道,从右边所看到的点从上到下分别是:顶点,右子树所能看到的点,左子树所能看到的比右子树要深的那些点(忽略右子树,视为透明)。因此,设f(node)返回从右边所看到的点,我们可以得到这样的一个递归式:

    ①若node为空,则看不到任何点,即返回空

    ②否则,f(node)=node->val+f(node->right)+f(node->left)[size( f(node->right) ),-1]


class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
            vector<int> temp;
            if(root==NULL)
                return temp;
            else
            {
                //顶点先放
                temp.push_back(root->val);
                
                //右边的点后放
                vector<int> right;
                right=rightSideView(root->right);
                for(int i=0;i<right.size();++i)
                    temp.push_back(right[i]);
                
                //左边的点index大于等于右边个数的点也放
                vector<int> left;
                left=rightSideView(root->left);
                for(int i=right.size();i<left.size();++i)
                    temp.push_back(left[i]);
                return temp;
            }
            
        }
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值