class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
vector<int>ans;
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
if(root==NULL)return ans;
postorderTraversal(root->left);
postorderTraversal(root->right);
ans.push_back(root->val);
return ans;
}
};
二叉树的后序遍历
class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
vector<int>ans;
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
if(root==NULL)return ans;
postorderTraversal(root->left);
postorderTraversal(root->right);
ans.push_back(root->val);
return ans;
}
};
给出一棵二叉树,返回其节点值的后序遍历。
样例
给出一棵二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [3,2,1]
解题思路:dfs遍历后序结构访问即可