LeetCode Binary Tree Postorder Traversal(二叉树的后序遍历 非递归实现)
2014-04-06 07:53
573 查看
题目要求:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree
return
用栈模拟递归过程, 后序要比其它两个遍历方式稍微复杂些, 要判断左右子节点都遍历后在访问根节点。
代码:
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].
用栈模拟递归过程, 后序要比其它两个遍历方式稍微复杂些, 要判断左右子节点都遍历后在访问根节点。
代码:
class Solution { public: vector<int> postorderTraversal(TreeNode *root) { stack<TreeNode*> st; vector<int> ret; if(root == NULL) return ret; TreeNode* cur = NULL; TreeNode* pre = NULL; st.push(root); while(!st.empty()) { cur = st.top(); if((cur->left == NULL && cur->right == NULL) || (pre != NULL && (cur->left == pre || cur->right == pre)))//如果是叶子节点或者是左右子孩子已经被访问过了,才能访问当前节点 { ret.push_back(cur->val); st.pop(); pre = cur; } else { if(cur->right != NULL) st.push(cur->right); if(cur->left != NULL) st.push(cur->left); } } return ret; } };
相关文章推荐
- 【LeetCode笔记】Construct Binary Tree from Inorder and Postorder Traversal 中序、后序遍历求二叉树
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序遍历建立二叉树
- Leetcode Construct Binary Tree from Inorder and Postorder Traversal 中序后序遍历重组二叉树
- LeetCode 145 Binary Tree Postorder Traversal (后序遍历二叉树)
- LeetCode: 106_Construct Binary Tree from Inorder and Postorder Traversal | 根据中序和后序遍历构建二叉树 | Medium
- [LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序遍历建立二叉树
- LeetCode-106:Construct Binary Tree from Inorder and Postorder Traversal (利用中序和后序遍历构建二叉树) -- medium
- Leetcode - Tree - 106. Construct Binary Tree from Inorder and Postorder Traversal(根据中序遍历和后序遍历重构二叉树)
- LeetCode 145: Binary Tree Postorder Traversal(二叉树的后序遍历,迭代法)
- 【LeetCode】Binary Tree Postorder Traversal 二叉树的后序遍历 - Easy
- Binary Tree Postorder Traversal 二叉树的后序遍历,使用堆栈,非递归
- LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal (用中序和后序树遍历来建立二叉树)
- 二叉树前/中/后序遍历非递归实现(用栈实现)LeetCode Binary Tree Traversal
- Construct Binary Tree from Inorder and Postorder Traversal 中序和后序遍历二叉树
- LeetCode-Construct Binary Tree from Inorder and Postorder Traversal-中序后序重构二叉树-递归
- Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal 中序和后序恢复二叉树
- LeetCode--Binary Tree Postorder Traversal(栈实现三种遍历)
- 【LeetCode-面试算法经典-Java实现】【107-Binary Tree Level Order Traversal II(二叉树层序遍历II)】
- LeetCode 145 Binary Tree Postorder Traversal(二叉树的后续遍历)+(二叉树、迭代)
- 【LeetCode-面试算法经典-Java实现】【107-Binary Tree Level Order Traversal II(二叉树层序遍历II)】