美文网首页
199. 二叉树的右视图

199. 二叉树的右视图

作者: lazy_ccccat | 来源:发表于2021-03-27 21:53 被阅读0次

    https://leetcode-cn.com/problems/binary-tree-right-side-view/

    层序遍历,非常好写,只是先右再左。

    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
            queue<TreeNode *> q;
            vector<int> res;
            if (!root) {
                return res;
            }
            q.push(root);
            while (!q.empty()) {
                int front_val = q.front()->val;
                res.push_back(front_val);
                int size = q.size();
                for (int i = 0; i < size; i++){
                    TreeNode* node = q.front();
                    if (node->right) q.push(node->right);
                    if (node->left) q.push(node->left);
                    q.pop();
                }
            }
            return res;
    
        }
    }
    

    另一种思路 dfs:
    https://leetcode-cn.com/problems/binary-tree-right-side-view/solution/jian-dan-de-shen-sou-by-bac0id-vj6a/

    相关文章

      网友评论

          本文标题:199. 二叉树的右视图

          本文链接:https://www.haomeiwen.com/subject/avfuhltx.html