LintCode 二叉树的后序遍历

题目描述:

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

您在真实的面试中是否遇到过这个题? Yes
样例
给出一棵二叉树 {1,#,2,3},

1
\
2
/
3
返回 [3,2,1]

思路分析:
dfs。

ac代码:

/**
 * 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> v;
    void mid(TreeNode *root)
    {
        if(root==NULL)
            return ;
        mid(root->left);
        mid(root->right);
        v.push_back(root->val);
    }
    vector<int> postorderTraversal(TreeNode *root) {
        // write your code here
        mid(root);
        return v;
    }
};
发布了166 篇原创文章 · 获赞 4 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/sinat_34336698/article/details/69787632