[leetcode]48 Binary Tree Right Side View

来源:互联网 发布:for在c语言中的作用 编辑:程序博客网 时间:2024/05/01 18:06

题目链接: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