199、Binary Tree Right Side View

来源:互联网 发布:linux 复制命令行 编辑:程序博客网 时间:2024/06/05 14:56

题目:

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

解题思路:

通过层次遍历,区该层的最后一个元素即为。

class Solution {public:    vector<int> res;        void dfs(TreeNode* root){        stack<TreeNode*> sta,tmp;        if(!root)return;        tmp.push(root);        while(!tmp.empty() || !sta.empty())        {            if(sta.empty() && !tmp.empty())            {                res.push_back(tmp.top()->val);                while(!tmp.empty())                {                    TreeNode* node2 = tmp.top(); tmp.pop();                    sta.push(node2);                }            }            TreeNode* node = sta.top(); sta.pop();            if(node->left)tmp.push(node->left);            if(node->right)tmp.push(node->right);        }    }    vector<int> rightSideView(TreeNode* root) {        dfs(root);        return res;    }};


0 0