0226

作者: 日光降临 | 来源:发表于2019-02-24 20:22 被阅读0次
      1. Invert Binary Tree
        Runtime: 4 ms, faster than 26.53% of C online submissions for Invert Binary Tree.
        Memory Usage: 7.5 MB, less than 37.04% of C online submissions for Invert Binary Tree.
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    void dfs(struct TreeNode* r){
        if(r==NULL)
            return;
        struct TreeNode* t;
        t = r->left;
        r->left = r->right;
        r->right = t;
        dfs(r->left);
        dfs(r->right);
    }
    struct TreeNode* invertTree(struct TreeNode* root) {
        dfs(root);
        return root;
    }
    
    • 下面这种写法是错误,出不来结果, 猜测是函数栈的问题
      用同样的方法,不另外写函数,在lintcode上用Java 提交是通过的。
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    struct TreeNode* invertTree(struct TreeNode* root) {
        if(root==NULL);
            return NULL;
        if(root->left!=NULL || root->right!=NULL){
            struct TreeNode *tmp = root->left;
            root->left = root->right;
            root->right = tmp;
        }
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
    

    相关文章

      网友评论

          本文标题:0226

          本文链接:https://www.haomeiwen.com/subject/kvgbyqtx.html