Leetcode:Invert Binary Tree

Invert Binary Tree

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.


Answer 

反轉 Binary Tree,一開始嘗試直接對root 底下的 left 和 right 互換,不過運行結果一直報錯,直到了解要 return node ...

Javascript

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root){
    if(root){
        var x = root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(x);
        return root;
    }else{
        return null;
    }
};
//Min:112ms
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/

C

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* invertTree(struct TreeNode* root){
    if(root){
        struct TreeNode* p = root->lrft;
        root->left = invertTree(root->right);
        root->right = invertTree(p);
        return root;
    }
}
//Min:0ms
_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/

Python

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if root != None:
            x = root.left;
            root.left = self.invertTree(root.right)
            root.right = self.invertTree(x)
            return root
        else:
            return None
#Min:36ms

留言

這個網誌中的熱門文章

Leetcode:Number of 1 Bits