题目描述:给出一棵二叉树,返回其节点值的后序遍历。
样例:
给出一棵二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [3,2,1]
做题思路:运用递归,先遍历左子树,再遍历右子树,最后遍历根,存入数组,返回数组。
关键代码:
class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
std::vector<int> w;
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
if(root==NULL) return w;
else {
postorderTraversal(root->left);
postorderTraversal(root->right);
w.push_back(root->val);
}
return w;
}
};
做题感想:和前几题的先序遍历,中序遍历一样。