Given a binary tree, return the postorder traversal of its nodes' values.
Example
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
解题思路:
递归。与前序遍历代码几乎相同,仅仅是位置不同。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: A Tree
* @return: Postorder in ArrayList which contains node values.
*/
vector<int> result;
vector<int> postorderTraversal(TreeNode * root)
{
// write your code here
if(root == NULL) return result;
if(root->left != NULL)
result = postorderTraversal(root->left);
if(root->right != NULL)
result = postorderTraversal(root->right);
result.push_back(root->val);
return result;
}
};
本文介绍了一种使用递归方法实现二叉树后序遍历的算法,并提供了具体的C++代码示例。该算法首先遍历左子树,然后遍历右子树,最后访问根节点。
1162

被折叠的 条评论
为什么被折叠?



