binary-tree-postorder-traversal
来源:互联网 发布:机床的重要性 知乎 编辑:程序博客网 时间:2024/06/09 19:41
binary-tree-postorder-traversal
Given a binary tree, return the *postorder*traversal of its nodes’ values.
For example:
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?
思想
首先看到二叉树后序遍历,很多人第一眼想到的是递归的方法,但题目强调用非递归的方法
所以可以考虑用栈,应为递归的实质实现还是通过栈
方法一
- 根节点入栈
- 访问栈顶节点(并不出栈)
- 如果栈顶节点左右孩子都为空,出栈,转6,否则进行4,5步
- 栈顶节点的右节点入栈(右节点不为空的条件下),栈顶节点的右节点赋值为NULL
- 栈顶节点的左节点入栈(左节点不为空的条件下),栈顶节点的左节点赋值为NULL
- 重复上述步骤2-5,直到栈为空
方法二
(方法一,改变了树的结构,方法二可以克服这个缺点,用一个map标记访问次数)
- 根节点入栈
- 访问栈顶节点(并不出栈)
- 如果栈顶节点左右孩子都为空,出栈 转7,否则进行步骤4
- 如果栈顶节点是第一次访问,进行步骤5,6,如果栈顶节点是第二次访问,出栈 转7
- 栈顶节点的右节点入栈(右节点不为空的条件下)
- 栈顶节点的左节点入栈(左节点不为空的条件下)
- 重复上述步骤2-6,直到栈为空
方法一代码
class Solution {public: vector<int> postorderTraversal(TreeNode *root) { vector<int>vec; if(root == NULL) return vec; stack<TreeNode*>st; st.push(root); TreeNode * cur = NULL; while(!st.empty()){ cur = st.top(); if(cur->left == NULL && cur->right == NULL){ vec.push_back(cur->val); st.pop(); }else{ if(cur->right){ st.push(cur->right); cur->right = NULL; } if(cur->left){ st.push(cur->left); cur->left = NULL; } } } return vec; }};
方法二代码
#include<vector>#include<stack>class Solution {public: vector<int> postorderTraversal(TreeNode *root) { vector<int> a; if(root == NULL) return a; stack<TreeNode*> b; /*标记访问次数*/ map<TreeNode*, int>c; b.push(root); TreeNode *temp; while(!b.empty()){ temp = b.top(); if(temp->left == NULL && temp->right == NULL) { a.push_back(temp->val); b.pop(); } else { if(c.count(temp) > 0) c[temp]++; else c[temp] = 1; if(c[temp] == 2) { a.push_back(temp->val); b.pop(); } else { if(temp->right != NULL) b.push(temp->right); if(temp->left != NULL) b.push(temp->left); } } } return a; }};
阅读全文
0 0
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- vue2.0
- android 自定义View之将字体绘制在Rect中间
- LeetCode: 65.Valid Number
- HDU 1159 Common Subsequence(最长公共子序列(LCS) 动态规划(DP))
- 医院刚刚严重发声,情况紧急!全民必看!
- binary-tree-postorder-traversal
- C#中使用seriport和单片机进行串口长数据收发不全,解决办法
- Python自定义模块并发布与安装
- SQL—授权grant与回收revoke
- 字典树(trie树)
- Python csv模块的使用
- Java基础总结-内存与变量
- Redis学习之限制请求频率及资源隔离详解
- SpringBoot定时任务及Cron表达式详解