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]
.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ /* 1)如果根节点非空,将根节点加入到栈中。 2)如果栈不空,取栈顶元素(暂时不弹出), 如果(左子树已访问过或者左子树为空),且(右子树已访问过或右子树为空),则弹出栈顶节点,将其值加入数组, 如果左子树不为空,且未访问过,则将左子节点加入栈中,并标左子树已访问过。 如果右子树不为空,且未访问过,则将右子节点加入栈中,并标右子树已访问过。 3)重复第二步,直到栈空。*/ struct stkNode { TreeNode *node; bool lVisited; bool rVisited; stkNode(TreeNode *p){node = p; lVisited= false; rVisited= false;} }; class Solution { public: vector<int> postorderTraversal(TreeNode* root) { stack<stkNode*> stk; vector<int> result; if(root==NULL) return result; stk.push( new stkNode(root)); while(!stk.empty()) { stkNode *stknode = stk.top(); if((!stknode->node->left || stknode->lVisited)&&(!stknode->node->right || stknode->rVisited)) { stk.pop(); result.push_back(stknode->node->val); delete stknode; }else if(stknode->node->left && !stknode->lVisited) { stk.push(new stkNode(stknode->node->left)); stknode->lVisited = true; }else if(stknode->node->right && !stknode->rVisited) { stk.push(new stkNode(stknode->node->right)); stknode->rVisited = true; } } return result; } };
时间: 2024-10-28 23:23:04