Binary Tree Right Side View

来源:互联网 发布:unity3d简介 编辑:程序博客网 时间:2024/06/08 03:49

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
原创粉丝点击