Given a binary tree, return the postorder traversal of its nodes‘ values.
For example:
Given binary tree [1,null,2,3]
,
1 2 / 3
思路: 借助于一个栈,依次将根节点的右子节点和左子节点压入栈中。如果一个节点为叶子节点,或者前一个出栈的元素为当前栈顶节点的子节点,则出栈。
vector<int> postorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode*> _stack; TreeNode *cur=root; TreeNode *pre=NULL; if(cur!=NULL) _stack.push(cur); while(!_stack.empty()) { cur=_stack.top(); if((cur->left==NULL&&cur->right==NULL)||(pre&&(cur->left==pre||cur->right==pre))) { res.push_back(cur->val); pre=cur; _stack.pop(); } else { if(cur->right) _stack.push(cur->right); if(cur->left) _stack.push(cur->left); } } return res; }