问题描述:
给出一棵二叉树,返回其节点值的后序遍历。
样例
给出一棵二叉树 {1,#,2,3},
1 \ 2 / 3返回 [3,2,1]
解题思路:用函数调用来写,写一个z后序遍历的函数,用递归的思想,在函数中调用。
代码:
/** * 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. */ void postorder(vector<int>&v,TreeNode *root){ if(root==NULL) return ; postorder(v,root->left); postorder(v,root->right); v.push_back(root->val); } public: vector<int> postorderTraversal(TreeNode *root) { vector<int> v; postorder(v,root); return v; // write your code here } };
感悟:
注意在后序遍历函数中的引用,可以认为是一个全局变量。