LeetCode 145:Binary Tree Postorder Traversal(后序遍历)
来源:互联网 发布:cisco网络交换机型号 编辑:程序博客网 时间:2024/09/21 09:05
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]
.
题目要求对二叉树进行非递归的后序遍历,所谓后序遍历即,先访问左子树、然后是右子树,最后访问根节点。通常采用递归的方法,题目要求采用非递归的方法实现。算法如下:
1)如果根节点非空,将根节点加入到栈中。
2)如果栈不空,取栈顶元素(暂时不弹出),
如果(左子树已访问过或者左子树为空),且(右子树已访问过或右子树为空),则弹出栈顶节点,将其值加入数组,
如果左子树不为空,切未访问过,则将左子节点加入栈中,并标左子树已访问过。
如果右子树不为空,切未访问过,则将右子节点加入栈中,并标右子树已访问过。
//包裹结构体 struct TreeNodeWrapper{struct TreeNode *pNode;bool lVisited;bool rVisited;TreeNodeWrapper(TreeNode * p){pNode = p; lVisited= false; rVisited= false;}}; class Solution {public: vector<int> postorderTraversal(TreeNode* root) {vector<int> result;stack<TreeNodeWrapper*> node_stack;if (root == NULL){return result;}node_stack.push(new TreeNodeWrapper(root));while(!node_stack.empty()){TreeNodeWrapper* pNode = node_stack.top();if ((!pNode->pNode->left ||pNode->lVisited ) && ( !pNode->pNode->right||pNode->rVisited)){ //左右子树都已访问过 node_stack.pop();result.push_back(pNode->pNode->val);delete pNode;}else{ if (!pNode->lVisited && pNode->pNode->left){//左子树不为空,且未访问过,则访问左子树node_stack.push(new TreeNodeWrapper(pNode->pNode->left));pNode->lVisited = true;}else{if (pNode->pNode->right){ //右子树不为空,且未访问过 node_stack.push(new TreeNodeWrapper(pNode->pNode->right));pNode->rVisited = true;}}}}return result;} };
1 0
- LeetCode 145:Binary Tree Postorder Traversal(后序遍历)
- 【leetcode】145Binary Tree Postorder Traversal(二叉树非递归后序遍历)
- 后序遍历 Binary Tree Postorder Traversal -- LeetCode
- 【leetcode 后序遍历】Binary Tree Postorder Traversal
- leetcode 145. Binary Tree Postorder Traversal 后序遍历
- ****(leetcode) Binary Tree Postorder Traversal (tree后序遍历非递归实现)
- binary-tree-postorder-traversal(后序遍历二叉树)
- LeetCode 145 Binary Tree Postorder Traversal(二叉树后序遍历)
- LeetCode 145: Binary Tree Postorder Traversal(二叉树的后序遍历,迭代法)
- LeetCode 145 Binary Tree Postorder Traversal (后序遍历二叉树)
- LeetCode OJ 之 Binary Tree Postorder Traversal (二叉树的后序遍历)
- 【LeetCode-面试算法经典-Java实现】【145-Binary Tree Postorder Traversal(二叉树非递归后序遍历)】
- Binary Tree Postorder Traversal-二叉树的后序遍历
- Binary Tree Postorder Traversal 二叉树的后序遍历
- 二叉树的后序遍历 Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal 二叉树的后序遍历
- LeetCode Binary Tree Postorder Traversal(二叉树的后序遍历 非递归实现)
- [LeetCode]145. Binary Tree Postorder Traversal--二叉树的后序遍历
- Linux命令常放置的位置与PATH变量设置 网上转载稍加修改
- html水平分割线标签
- Fedora安装jdk---适用于个人使用
- ibatis笔记
- linux:将自己的程序添加到应用程序
- LeetCode 145:Binary Tree Postorder Traversal(后序遍历)
- 解决apache启动错误:Could not reliably determine the server's fully qualified domain name
- tomcat 软连接问题
- java多线程
- MySql 数据库 新建 字符集与字符校对设置
- JMS笔记
- Mailto Protocol电子邮件协议
- jquery笔记
- 设计模式笔记1