问题描述:
给出一棵二叉树,返回其节点值的后序遍历。
实现思路:
创建动态数组来存放节点的值。利用递归的思想。
实现代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
std::vector<int> v;
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
if (root != NULL)
{
postorderTraversal(root->left);
postorderTraversal(root->right);
v.push_back(root->val);
}
return v;
}
};
感想:
和前序遍历、中序遍历类似,由定义可知可以利用递归的思想。考虑root为空的情况。