LeetCode-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.
题目大意
给一棵二叉树,我们站在二叉树的右边,输出从树根到树叶能看到的结点的数值。
示例
E1
Input: [1,2,3,null,5,null,4] Output: [1, 3, 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; } };