199. 二叉树的右视图

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

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

class Solution {
public:
    vector rightSideView(TreeNode* root) {
        queue q;
        vector 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. 二叉树的右视图)