加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

LeetCode-199 Binary Tree Right Side View

发布时间:2020-12-14 04:44:57 所属栏目:大数据 来源:网络整理
导读:题目描述 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. ? 题目大意 给一棵二叉树,我们站在二叉树的右边,输出从树根到树叶能看到的结点的数值。 ?

题目描述

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.

?

题目大意

给一棵二叉树,我们站在二叉树的右边,输出从树根到树叶能看到的结点的数值。

?

示例

E1

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

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

?

解题思路

利用两个stack来保存树每层的结点,保存该层最靠右的结点的数值。

?

复杂度分析

时间复杂度:O(n)

空间复杂度:O(n)

?

代码

/**
 * Definition for a binary tree node.
 * 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) {
        stack<TreeNode*> str,stran;
        vector<int> res;
        //将根节点入栈
        if(root != NULL)
            str.push(root);
        
        //遍历树的结点
        while(!str.empty()) {
            TreeNode* tmp;
            //保存最靠右的树结点,也就是栈顶元素
            tmp = str.top();
            res.push_back(tmp->val);
            //为了保证栈顶一定为每一层最靠右的结点,需要用另一个栈来进行操作
            //将下一层的结点按从右到左的顺序如另一个栈
            while(!str.empty()) {
                if(tmp->right != NULL)
                    stran.push(tmp->right);
                if(tmp->left != NULL)
                    stran.push(tmp->left);
                str.pop();
                if(!str.empty())
                    tmp = str.top();
            }
            //为保证栈顶为最右结点,将另一个栈中元素按序存入循环使用的栈中
            if(!stran.empty())
                tmp = stran.top();
            while(!stran.empty()) {
                str.push(tmp);
                stran.pop();
                if(!stran.empty())
                    tmp = stran.top();
            }
        }
        
        return res;
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读