Leetcode 199. 二叉树的右视图 二叉树的遍历

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:

输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

此题有两种解法,一种是二叉树的层序遍历,一种是递归左右子树。。

1.层序遍历:
 只需要在普通的层序遍历中的先遍历左子树再右子树的顺序颠倒即可。。。即先右子树再左子树,然后取队首元素即可。。

 代码如下:
 

/**
 * 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> re;
        if(root==NULL)
            return re;
        queue<TreeNode*>q;
        q.push(root);
        while (!q.empty())
        {
            int Size=q.size();
            if(Size)
                re.push_back(q.front()->val); //取出元素
            while (Size--)
            {
                TreeNode* t=q.front();
                q.pop();
                if(t->right)
                    q.push(t->right);
                if(t->left)
                    q.push(t->left);
            }
        }
        return re;
    }
};

耗时:4ms 

2递归遍历:

 先递归右子树,再递归左子树, 如果节点的值比当前最大高度高的话, 直接push进去。 。

代码如下:
 

/**
 * 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:
    int Maxdep=0;
    vector<int> re;
    vector<int> rightSideView(TreeNode* root) {
          if(root==NULL)
              return re;
          traverse (root,1);
          return re;
    }
    void traverse (TreeNode* root,int depth)
    {
        if(depth>Maxdep)
        {
            re.push_back(root->val);
            Maxdep=depth;
        }
        if(root->right)
            traverse (root->right,depth+1);
        if(root->left)
            traverse (root->left,depth+1);
    }
    
};

猜你喜欢

转载自blog.csdn.net/qq_41410799/article/details/82556596