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

这个题,我的首先想到的思路就是:层序遍历,使用队列实现,但是为了找到每一层的最后一个我需要放入一个标示位(NULL),这和我之前面过的一个分层打印的面试题差不多,代码如下:

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        queue<TreeNode*> level_tree;
        vector<int> ans;
        if(!root) return ans;
        auto t_root=root;
        level_tree.push(t_root);
        level_tree.push(NULL);
        while(!level_tree.empty()){
            auto temp=level_tree.front();
            level_tree.pop();
            if(level_tree.empty()) break;
            if(level_tree.front()==NULL){
                ans.push_back(temp->val);
                if(temp->left) level_tree.push(temp->left);
                if(temp->right) level_tree.push(temp->right);
                //if(temp->left||temp->right) 
                level_tree.push(NULL);
                //else break;
                level_tree.pop();
            }else{
                if(temp->left) level_tree.push(temp->left);
                if(temp->right) level_tree.push(temp->right);
            }
        }
        return ans;
    }
};
也能完成功能,但是还不够好,我查看下discuss中的方法, 有一个和我的类似但是没有这么麻烦的思路:使用队列存放一层的元素,取出它们的大小,循环地弹出头部元素再把头的左右子节点放入队列中,对于每一层只需要把队列尾部的元素取出就行了,代码如下:

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

这只是迭代法,如果使用递归, 需要用后序遍历,同时还需要一个重要参数存放树的层数,代码如下:

class Solution {
public:
    void recursion(TreeNode *root, int level, vector<int> &res)
    {
        if(root==NULL) return ;
        if(res.size()<level) res.push_back(root->val);
        recursion(root->right, level+1, res);
        recursion(root->left, level+1, res);
    }

    vector<int> rightSideView(TreeNode *root) {
        vector<int> res;
        recursion(root, 1, res);
        return res;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值