Leetcode Binary Tree Postorder Traversal(面试题推荐)
来源:互联网 发布:c语言 sleep用法 编辑:程序博客网 时间:2024/06/16 22:05
此题来自leetcode https://oj.leetcode.com/problems/binary-tree-postorder-traversal/
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
非递后续归遍历二叉树,肯定得用到栈。先序遍历很好写,但后续遍历就不是那么容易了。只需要设置个指针pre,指向最后输出的那个节点就行了,只要判断cur指针指向的是上次输出节点的父节点,且cur无其他未遍历的节点,这个时候就把cur节点输出即可,然后更改pre。原理是要遍历当前节点,其所有子节点都必须遍历完,因为肯定是先左后右,所以只需一个指针保持前一次输出的结果即可。
/** * 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> postorderTraversal(TreeNode *root) { vector<int> v; if (NULL == root) return v; stack<TreeNode*> s; s.push(root); TreeNode * pre = root; while (!s.empty()) { TreeNode * cur = s.top(); if ((NULL == cur->left && NULL == cur->right) || (pre == cur->left || pre == cur->right)) { s.pop(); v.push_back(cur->val); pre = cur; } else { if (cur->right) s.push(cur->right); if (cur->left) s.push(cur->left); } } return v; }};
0 0
- Leetcode Binary Tree Postorder Traversal(面试题推荐)
- LeetCode Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- [LeetCode] Binary Tree Postorder Traversal
- leetcode Binary Tree Postorder Traversal
- 【LeetCode】Binary Tree Postorder Traversal
- LeetCode | Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal - LeetCode
- LeetCode - Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal -- LeetCode
- [LeetCode]Binary Tree Postorder Traversal
- 【基础】使用Ansible连接AWS EC2
- Spring面向切面编程AOP
- uva442(Matrix Chain Multiplication)—线性表
- Android中数据存储之Shared Preference
- eclipse设置超时时间。Problems During Content Assist
- Leetcode Binary Tree Postorder Traversal(面试题推荐)
- Widevine *DRM and Keybox
- Elasticsearch相关图分享
- String s =new String()分析堆与栈
- /*C++任意输入一个整数,再把它的各位数字重新组合一个新的整数,使其值最大*/
- at android.widget.ListView.clearRecycledState(ListView.java:522)
- Decode Ways & String to Integer & Reverse Words in a String
- windows 8 中文乱码
- 大数类模板(+-*/%等等)