Binary Tree Postorder Traversal

来源:互联网 发布:中情局又遭曝光 知乎 编辑:程序博客网 时间:2024/05/21 09:24

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?


题目解析:

(1)因为根节点需要最后访问,下面的方法会损坏原来树的结构,因为无法判断当前节点的右子树是否已经全部进栈了。


#include <iostream>#include <vector>#include <stack>using namespace std;struct TreeNode {    int val;    TreeNode *left;    TreeNode *right;    TreeNode(int x) : val(x), left(NULL), right(NULL) {}};vector<int> postorderTraversal(TreeNode *root) {vector<int> result;if(root == NULL)return result;stack<TreeNode *> nodes;nodes.push(root);TreeNode *node = nodes.top();while (node->left!=NULL){nodes.push(node->left);node = node->left;}while (!nodes.empty()){TreeNode *node = nodes.top();if (node->right!=NULL){TreeNode *p = node;nodes.push(node->right);node = node->right;<strong><span style="color:#FF0000;">p->right = NULL;</span></strong>while (node->left!=NULL){nodes.push(node->left);node = node->left;}}else{result.push_back(node->val);nodes.pop();}}return result;}int main(void){system("pause");return 0;}


0 0