1.描述
给出一颗二叉树,返回其节点值的后序遍历。
样例
给出一棵二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [3,2,1]
2.分析
后序遍历首先遍历左子树,然后遍历右子树,最后访问根结点,在遍历左、右子树时,仍然先遍历左子树,然后遍历右子树,最后遍历根结点。即:
若
二叉树为空则结束返回,
否则:
(1)后序遍历左子树
(2)后序遍历右子树
(3)访问根结点
3.代码
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
void pre(vector<int> &v,TreeNode *root)
{
if(root==NULL) return;
else
{
pre(v,root->left);
pre(v,root->right);
v.push_back(root->val);
}
}
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
vector<int> v;
pre(v,root);
return v;
}
};
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
void pre(vector<int> &v,TreeNode *root)
{
if(root==NULL) return;
else
{
pre(v,root->left);
pre(v,root->right);
v.push_back(root->val);
}
}
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
vector<int> v;
pre(v,root);
return v;
}
};
4.总结
已知前序遍历和中序遍历,就能确定后序遍历。过程和前序中序遍历类似,只是先访问左右子树最后是根节点。