[Leetcode 199, Medium] Binary Tree Right Side View
2015-05-04 10:47
399 查看
Problem:
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,
You should return
Analysis:
Solutions:
C++:
Python:
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].
Analysis:
Solutions:
C++:
vector<int> rightSideView(TreeNode *root) { vector<int> result; if(!root) return result; vector<TreeNode *> visible_pointer_array; stack<TreeNode *> cached_nodes; TreeNode *pCurrNode = root; int index = 0; while(pCurrNode || !cached_nodes.empty()) { if(pCurrNode) { if(index == visible_pointer_array.size()) visible_pointer_array.push_back(pCurrNode); else if(index < visible_pointer_array.size()) visible_pointer_array[index] = pCurrNode; ++index; cached_nodes.push(pCurrNode); } if(pCurrNode && pCurrNode->left) pCurrNode = pCurrNode->left; else { pCurrNode = cached_nodes.top(); cached_nodes.pop(); int i = visible_pointer_array.size() - 1; for(; i >= 0 ; --i) { if(pCurrNode == visible_pointer_array[i]) break; } index = i + 1; pCurrNode = pCurrNode->right; } } for(int i = 0; i < visible_pointer_array.size(); ++i) result.push_back(visible_pointer_array[i]->val); return result; }Java:
Python:
相关文章推荐
- 199.leetcode Binary Tree Right Side View(medium)[层次遍历二叉树 队列]
- LeetCode #199 - Binary Tree Right Side View - Medium
- Binary Tree Right Side View - LeetCode 199
- Leetcode 199 Binary Tree Right Side View 二叉树右视图
- leetcode-199 Binary Tree Right Side View
- [LeetCode] 199 - Binary Tree Right Side View
- 【LeetCode-面试算法经典-Java实现】【199-Binary Tree Right Side View(从右边看二叉树)】
- leetCode 101/199-Symmetric Tree/Binary Tree Right Side View
- 【小熊刷题】Binary Tree Right Side View <Leetcode 199, Java>
- LeetCode - 199 - Binary Tree Right Side View
- [leetcode-199]Binary Tree Right Side View(java)
- LeetCode(199) Binary Tree Right Side View解题报告
- Leetcode 199 Binary Tree Right Side View 二叉树右视图
- [LeetCode 199] Binary Tree Right Side View (递归的层数)
- [leetcode] 199. Binary Tree Right Side View
- [Leetcode] #199 Binary Tree Right Side View
- leetcode 199: Binary Tree Right Side View
- Leetcode 199: Binary Tree Right Side View
- leetcode_199题——Binary Tree Right Side View(广度优先搜索,队列queue)
- LeetCode #199 - Binary Tree Right Side View