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].
实际上就是求每一层的最右元素,我的第一想法是广度优先遍历,然后把每一层最右边的元素输出。然后就AC了!

/**
 * 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 rightSideView(TreeNode* root) {
        vector res;
        if (root == NULL)
            return res;
        queue s;
        s.push(root);
        s.push(NULL);
        while (s.front() != NULL) {
            TreeNode *tmp = NULL;
            while (s.front() != NULL) {
                tmp = s.front();
                s.pop();
                if (tmp->left)
                    s.push(tmp->left);
                if (tmp->right)
                    s.push(tmp->right);
            }
            if (tmp)
                res.push_back(tmp->val);
            s.pop();
            s.push(NULL);
        }
        return res;
    }
};

然后看了下大神们的做法,用的深度优先的方法,先向右搜索,到底了之后再向左,然后继续向右向下深度优先。代码如下:

class Solution {
public:
    void recursion(TreeNode *root, int level, vector &res)
    {
        if(root==NULL) return ;
        if(res.size()val);
        recursion(root->right, level+1, res);
        recursion(root->left, level+1, res);
    }
    
    vector rightSideView(TreeNode *root) {
        vector res;
        recursion(root, 1, res);
        return res;
    }
};

你可能感兴趣的:(Binary Tree Right Side View)