LeetCode:145_Binary Tree Postorder Traversal | 二叉树后序遍历 | Hard

题目:Binary Tree Postorder Traversal

二叉树的后序遍历,题目要求是采用非递归的方式,这个在上数据结构的课时已经很清楚了,二叉树的非递归遍历不管采用何种方式,都需要用到栈结构作为中转,代码很简单,见下:

 struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(NULL),right(NULL) {}
}; vector<int> preorderTraversal(TreeNode *root) //非递归的后序遍历(用栈实现)
{
if (NULL == root) {
return vector<int>();
} stack<TreeNode *> tree_stack;
vector<int> tree_vector; tree_stack.push(root);
TreeNode *p = NULL;
while (!tree_stack.empty()) {
TreeNode *pTemp = tree_stack.top();
if ((pTemp->left == NULL && pTemp->right == NULL) || ((p != NULL) && (pTemp->left == p || pTemp->right == p))) {
tree_vector.push_back(pTemp->val);
tree_stack.pop(); p = pTemp;
}
else {
while(pTemp) {
if (pTemp->right != NULL)
tree_stack.push(pTemp->right); if (pTemp->left != NULL)
tree_stack.push(pTemp->left);
pTemp = pTemp->left;
}
}
}
return tree_vector;
}
上一篇:利用google api生成二维码名片例子


下一篇:[POJ 2019] Cornfields