199. 二叉树的右视图

这道题非常的好。可以用depth-first search 以及breadth-first两种解法。参考了

https://leetcode-cn.com/problems/binary-tree-right-side-view/solution/liang-chong-jie-ti-fang-fa-di-gui-ji-bai-100he-fei/

并且depth-first search 不是通常意义上的前序,后以及中序遍历。并且要对depth 进行判断。

breadth-first每次访问的都是每层的最后一个元素,也就是最右边的元素。

class Solution {

public:

    vector<int> ans;

    void depthSearch(TreeNode* root, vector<int>& res, int level){

        if(!root) return;

        if(res.size() == level) res.push_back(root->val);

        depthSearch(root->right, res, level+1);

        depthSearch(root->left, res, level+1); 

    }

    // this is for depth-first traverse

    vector<int> rightSideView1(TreeNode* root){

        int level(0);

        vector<int> res;

        if(!root) return res;

        res.push_back(root->val);

        depthSearch(root, res, level);

        return res;

    }

    // this is for breadth-first search 

    vector<int> rightSideView(TreeNode* root) {

        if(root == NULL) return ans;

        queue<TreeNode*> nodePath;

        nodePath.push(root);

        TreeNode* current = new TreeNode(0);

        while(!nodePath.empty()){

            ans.push_back(nodePath.back()->val);

            int queue_size = nodePath.size();

            while(queue_size--){

                current = nodePath.front(); nodePath.pop();

                if(current->left) nodePath.push(current->left);

                if(current->right) nodePath.push(current->right);

            }

        }     

        return ans;

        }

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值