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?
class Solution { public: vector<int> postorderTraversal(TreeNode *root) { vector<int> result; if(!root) return result; stack<MyNode*> treeStack; MyNode* myRoot = new MyNode(root); MyNode* current, *newNode; treeStack.push(myRoot); while(!treeStack.empty()) { current = treeStack.top(); treeStack.pop(); if(!current->flag) { current->flag = true; treeStack.push(current); if(current->node->right) { newNode = new MyNode(current->node->right); treeStack.push(newNode); } if(current->node->left) { newNode = new MyNode(current->node->left); treeStack.push(newNode); } } else { result.push_back(current->node->val); } } return result; } struct MyNode { TreeNode* node; bool flag; //indicate if the node has been visited MyNode(TreeNode* x) : node(x),flag(false) {} }; };
时间: 2024-10-29 19:08:04