leetcode 145. Binary Tree Postorder Traversal
来源:互联网 发布:stm32编程步骤 编辑:程序博客网 时间:2024/06/13 21:54
相关问题
144. Binary Tree Preorder Traversal
94. Binary Tree Inorder Traversal
145. Binary Tree Postorder Traversal
Discription
Given a binary tree, return the postorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
思路
方法一
树的后序遍历比较复杂
先遍历左子树,第一次返回根节点;
再遍历右子树,第二次返回根节点;
所以需要变量记录当前状态,是在访问左子树还是在访问右子树。
时间复杂度:
空间复杂度:
代码
代码
/** * 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> postorderTraversal(TreeNode* root) { vector<int> res; vector<TreeNode*> sta; bool forward = true; //访问左子树 TreeNode *preVisited = NULL; if (root) sta.push_back(root); while (!sta.empty()) { while (sta.back()->left && forward) sta.push_back(sta.back()->left); forward = false; if (!sta.back()->right || sta.back()->right == preVisited) { // 右节点已经访问过了 res.push_back(sta.back()->val); preVisited = sta.back(); sta.pop_back(); } else { sta.push_back(sta.back()->right); forward = true; } } return res; }};
阅读全文
0 0
- [LeetCode]145.Binary Tree Postorder Traversal
- [leetcode] 145.Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal LeetCode
- Leetcode 145. Binary Tree Postorder Traversal
- [LeetCode]145. Binary Tree Postorder Traversal
- Leetcode 145. Binary Tree Postorder Traversal
- leetcode 145. Binary Tree Postorder Traversal
- LeetCode 145. Binary Tree Postorder Traversal
- LeetCode-145.Binary Tree Postorder Traversal
- [leetcode] 145. Binary Tree Postorder Traversal
- LeetCode 145. Binary Tree Postorder Traversal
- leetcode 145. Binary Tree Postorder Traversal
- [LeetCode]problem 145. Binary Tree Postorder Traversal
- Leetcode 145. Binary Tree Postorder Traversal
- [LeetCode] 145. Binary Tree Postorder Traversal
- LeetCode 145. Binary Tree Postorder Traversal
- LeetCode 145. Binary Tree Postorder Traversal
- LeetCode:145. Binary Tree Postorder Traversal
- js给dom元素绑定事件的三种方式
- Lucene3.0之结果排序(原理篇)
- angularjs添加数据展示或隐藏数据
- iOS Vim的保存文件和退出命令
- (linux)ubuntu 16.04 安装 log4cxx
- leetcode 145. Binary Tree Postorder Traversal
- 广播(BroadCast)
- 深度学习基础
- 论文代发技巧
- VScode设置
- 嵌入式开发(ARM9)学习笔记(五)-Red hat配置opencv
- Leetcode(W5):126. Word Ladder II
- mtk lk部分的振动器驱动
- python画等边三角形及彩蟒