Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

226. Invert Binary Tree #191

Open
Tcdian opened this issue Jun 1, 2020 · 1 comment
Open

226. Invert Binary Tree #191

Tcdian opened this issue Jun 1, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Jun 1, 2020

226. Invert Binary Tree

翻转一棵二叉树。

Example

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1
@Tcdian
Copy link
Owner Author

Tcdian commented Jun 1, 2020

Solution

  • JavaScript Solution
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root) {
    if (root === null) {
        return null;
    }
    const invertedLeft = invertTree(root.left);
    const invertedRight = invertTree(root.right);
    root.left = invertedRight;
    root.right = invertedLeft;
    return root;
};
  • TypeScript Solution
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function invertTree(root: TreeNode | null): TreeNode | null {
    if (root === null) {
        return null;
    }
    const invertedLeft = invertTree(root.left);
    const invertedRight = invertTree(root.right);
    root.left = invertedRight;
    root.right = invertedLeft;
    return root;
};

@Tcdian Tcdian added the Tree label Jun 1, 2020
@Tcdian Tcdian added the Classic label Sep 16, 2020
@Tcdian Tcdian removed the Classic label Jul 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant