给定一棵二叉树,返回其节点值的后序遍历。
例如:
给定二叉树 [1,null,2,3],
1
\
2
/
3
返回 [3,2,1]。
注意: 递归方法很简单,你可以使用迭代方法来解决吗?
详见:https://leetcode.com/problems/binary-tree-postorder-traversal/description/
方法一:递归
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; if(root==nullptr) { return res; } return postorderTraversalHelper(root,res); } vector<int> postorderTraversalHelper(TreeNode* root,vector<int> &res) { if(root==nullptr) { return res; } postorderTraversalHelper(root->left,res); postorderTraversalHelper(root->right,res); res.push_back(root->val); return res; } };
方法二:非递归
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; if(root==nullptr) { return res; } stack<TreeNode*> stk1; stack<TreeNode*> stk2; stk1.push(root); while(!stk1.empty()) { root=stk1.top(); stk1.pop(); stk2.push(root); if(root->left) { stk1.push(root->left); } if(root->right) { stk1.push(root->right); } } while(!stk2.empty()) { root=stk2.top(); stk2.pop(); res.push_back(root->val); } return res; } };