题解 | 输出二叉树的右视图

输出二叉树的右视图

https://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0

#include <ios>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 求二叉树的右视图
     * @param preOrder int整型vector 先序遍历
     * @param inOrder int整型vector 中序遍历
     * @return int整型vector
     */
    //建树
    TreeNode* buildTree(vector<int>& preOrder,int left1,int right1,vector<int>& inOrder,int left2,int right2)
    {
        if(left1>right1||left2>right2)
        {
            return nullptr;
        }
        int rootlocation=-1;
        for(int i=left2;i<=right2;i++)
        {
            if(inOrder[i]==preOrder[left1])
            {
                rootlocation=i;
                break;
            }
        }
       TreeNode* root = new TreeNode(preOrder[left1]);
       TreeNode* left = buildTree(preOrder,left1+1,right1-(right2-rootlocation),inOrder,left2,rootlocation-1);//左子树的前序、中序
       TreeNode* right = buildTree(preOrder,right1-(right2-rootlocation)+1,right1,inOrder,rootlocation+1,right2);//右子树的前序、中序
       root->left=left;
       root->right=right;
       return root;
        
    }
    //考虑层级遍历和DFS两种方法,这里只用DFS
    //目的是找到每一层的最右节点
    //先递归右子树,再递归左子树
    void rightdfs(TreeNode* root,int depth,vector<int> &res)
    {
       if(root==nullptr)
       {
            return;
       }
       //根节点是第一层的最右节点,考虑第一次将根节点放入,所以depth的初值应为0
       //自顶向下
       if(depth==res.size())//深度和res的大小如果相等,则说明是第一次进来,因为每一层只放一个最右节点值
       {
        res.push_back(root->val);
       }
       //每一层都是从右节点开始,没有就找左节点,都没有就停止递归
       rightdfs(root->right,depth+1,res);
       rightdfs(root->left,depth+1,res);
    }
    vector<int> solve(vector<int>& preOrder, vector<int>& inOrder) {
        // write code here
        vector<int> res;
      if(preOrder.size()==0||inOrder.size()==0)
      {
        return res;
      }
      TreeNode* root = buildTree(preOrder, 0, preOrder.size()-1,inOrder, 0, inOrder.size()-1);//得到新的二叉树
      rightdfs(root, 0, res);
      return res;
    }
};

全部评论

相关推荐

用微笑面对困难:你出于礼貌叫了人一声大姐,大姐很欣慰,她真把你当老弟
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务