[leetcode]48 Binary Tree Right Side View

题目链接:https://leetcode.com/problems/binary-tree-right-side-view/
Runtimes:9ms

1、问题

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

2、分析

说到底,就是求一棵树的右侧面照,即每一层从右往左第一个数字。肯定是分层遍历,但是这个过程有优化的地方,以前做类似分层遍历题目的时候都是多开几个大vector存储数据,现在又有了新的辨别方式,剩下了很多空间以及时间。

3、小结

只要记录一层最后访问的那个节点即可,即preh < h时,pret就是要求的最后节点。用队列会和遍历的顺序一样,选择正确的数据结构也是很重要的。

4、实现

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode *root) {
        queue <TreeNode *> tv;
        queue <int> iv;
        vector<int> rv;
        if(NULL == root)
            return rv;
        tv.push(root);
        iv.push(1);
        int preh = INT_MAX;
        TreeNode *pret;
        while(!tv.empty())
        {
            TreeNode * t = tv.front(); tv.pop(); 
            int h = iv.front(); iv.pop();
            if(preh < h)
                rv.push_back(pret->val);
            if(NULL != t->left)
            {
                tv.push(t->left);
                iv.push(h + 1);
            }
            if(NULL != t->right)
            {
                tv.push(t->right);
                iv.push(h + 1);
            }
            preh = h;
            pret = t;
        }
        rv.push_back(pret->val);
        return rv;
    }
};

5、反思

从编程之美吸收了很多优化方法,一本不错的书。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值