题目:给出一棵二叉树,返回其节点值的后序遍历。
样例
给出一棵二叉树 {1,#,2,3}
,
1
2
/
3
返回 [3,2,1]
挑战
你能使用非递归实现么?
解:递归解,非递归以后补充
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /* * @param root: A Tree * @return: Postorder in ArrayList which contains node values. */ vector<int> postorderTraversal(TreeNode * root) { // write your code here vector<int> re; if(root!=NULL) { postorder(root,re); } return re; } void postorder(TreeNode* node,vector<int> &re) { if(node==NULL) return; if(node->left!=NULL) postorder(node->left,re); if(node->right!=NULL) postorder(node->right,re); re.push_back(node->val); } };