0226

2019-02-24  本文已影响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;
}
上一篇下一篇

猜你喜欢

热点阅读