您的位置:首页 > 其它

Lintcode 68 二叉树的后序遍历

2016-08-28 18:34 176 查看
描述:

给出一棵二叉树,返回其节点值的后序遍历。

样例:

给出一棵二叉树 {1,#,2,3},

返回 [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 {
/**
* @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)
{
postorderTraversal(root->left);
postorderTraversal(root->right);
ans.push_back(root->val);
}
return ans;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树 递归 遍历