199. Binary Tree Right Side View

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

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---'

方法1: dfs

思路:

(错误的思路,并不是) 实际上要返回的就是第一条dfs的路径,沿途记下所有途径节点值,到叶节点之后就可以结束了(right view可以来自多条路径的组合,如果自右至左一条比一条长)。

(正确的) preorder,dfs中传递一个level, 只有当result大小被第一次拓展,才将该节点记录。


class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> result;
        rightHelper(root, result, 0);
        return result;
    }
    
    void rightHelper(TreeNode * root, vector<int> & result, int depth){
        if (!root) return;
        if (result.size() == depth) result.push_back(root -> val);
        
        rightHelper(root -> right, result, depth + 1);
        rightHelper(root -> left, result, depth + 1);
        return;
    }
};

方法2: bfs

思路:

层序遍历,仅把第n个数推进result。

// 方法2: BFS, 在获取层大小后,当且仅当第n次pop才push_back到result
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        if (!root) return {};
        queue<TreeNode*> q;
        vector<int> res;
        q.push(root);
        while(!q.empty()) {
            int sz = q.size();
            while (sz-- > 0) {
                TreeNode * top = q.front();
                q.pop();
                
                if (sz == 0) res.push_back(top -> val);
                if (top -> left) q.push(top -> left);
                if (top -> right) q.push(top -> right);
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值