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

解法一(层序遍历BFS):

vector<int> rightSideView(TreeNode* root) {
        vector<int> res;
        if(root == NULL) return res;
        queue<TreeNode*> que;
        int cnt = 1, num = 0;
        que.push(root);
        while(!que.empty()){
            res.push_back(que.front() -> val);
            for(int i = 0; i<cnt; i++){
                TreeNode* tmp = que.front();
                que.pop();
                if(tmp -> right){
                    que.push(tmp -> right);
                    num++;
                }
                if(tmp -> left){
                    que.push(tmp -> left);
                    num++;
                }
            }
            cnt = num;
            num = 0;
        }
        return res;
    }

解法二(DFS改进的先序遍历,参数中使用level标识层数):

vector<int> rightSideView(TreeNode* root) {
        vector<int> res;
        dfs(root, 1, res);
        return res;
    }
    
    void dfs(TreeNode* root, int level, vector<int>& res) {
        if(root == NULL) return;
        if(level > res.size()) res.push_back(root -> val);
        dfs(root -> right, level+1, res);
        dfs(root -> left, level+1, res);
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容