[leetcode]Binary Tree Postorder Traversal
来源:互联网 发布:2016酒店业数据 编辑:程序博客网 时间:2024/06/16 17:34
Binary Tree Postorder Traversal
Difficulty:Hard
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?
虽然是Hard,但其实就是二叉树的后序遍历,说递归很简单,能不能用迭代来做。
我的做法就是用栈来实现遍历,栈用的每一个元素保存当前元素和当前元素的父节点,一开始把根(父节点为NULL)放入栈,如果栈顶元素的左右子树存在,就按照先右子树,再左子树的顺序入栈,如果没有子树则输出该节点,并把该节点从树中删除,再把栈顶出栈,重复这些操作直到栈空。
vector<int> postorderTraversal(TreeNode* root) { stack<pair<TreeNode*, TreeNode*>> s; vector<int> result; if (root == NULL) return result; pair<TreeNode*, TreeNode*> tmp(root, NULL);//根节点 s.push(tmp); while (s.size() > 0){ pair<TreeNode*, TreeNode*> p = s.top(); if (p.first->right != NULL){//右子树入栈pair<TreeNode*, TreeNode*> tmp(p.first->right, p.first); s.push(tmp); } if (p.first->left != NULL){//左子树入栈 pair<TreeNode*, TreeNode*> tmp(p.first->left, p.first); s.push(tmp); } if (p.first->right == NULL&&p.first->left == NULL){//没有子树 result.push_back(p.first->val);//输出值 if (p.second != NULL){//把叶子从树中删除 if (p.second->left == p.first) p.second->left = NULL; if (p.second->right == p.first) p.second->right = NULL; delete p.first; s.pop(); } else{ s.pop(); } } } return result; }
阅读全文
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
- 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
- 【LeetCode】Binary Tree Postorder Traversal
- Android AutoLayout
- ActiveMQ
- R6010 -abort() has been called错误
- Kotlin——初始Kotlin及Android Studio配置环境开发HelloKotlin
- 树链剖分总结
- [leetcode]Binary Tree Postorder Traversal
- JMS java 消息机制
- 数字货币开发专题(PoS挖矿教程普通电脑即可挖矿)
- 线上运维哪些事
- Android 实现左右两个ListView共同滑动
- SpringMVC 视图解析器
- 单调栈——hdu5726 GCD
- Ubuntu下如何安装TensorFlow
- 【二】【selenium+python】发现页面元素的方法介绍