Binary Tree Postorder Traversal
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?
解题思路
二叉树后序遍历的非递归算法,代码如下:
/**
* 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> result;
if (root == NULL) return result;
TreeNode *pre = NULL; // 指向上一次 “输出” 的节点
stack<TreeNode *> nodeStack;
nodeStack.push(root);
while (!nodeStack.empty()) {
TreeNode *cur = nodeStack.top();
if (((pre != NULL) && (cur->left == pre || cur->right == pre))
|| (cur->left == NULL && cur->right == NULL)) {
/* 如果当前节点为叶节点,或者左右子树均已经被访问输出,则直接输出该节点,
* 将其出栈并将其设为上一个访问的节点 。
*/
nodeStack.pop();
result.push_back(cur->val);
pre = cur;
}
else {
// 先入右子女,在入左子女
if (cur->right != NULL) nodeStack.push(cur->right);
if (cur->left != NULL) nodeStack.push(cur->left);
}
}
return result;
}
};