Skip to content

Latest commit

 

History

History
137 lines (96 loc) · 3.34 KB

invert-binary-tree.md

File metadata and controls

137 lines (96 loc) · 3.34 KB

226. Invert Binary Tree - 翻转二叉树

Tags - 题目标签

Description - 题目描述

EN:

Given the root of a binary tree, invert the tree, and return its root.

 

Example 1:

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Example 2:

Input: root = [2,1,3]
Output: [2,3,1]

Example 3:

Input: root = []
Output: []

 

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

ZH-CN:

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

 

示例 1:

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

示例 2:

输入:root = [2,1,3]
输出:[2,3,1]

示例 3:

输入:root = []
输出:[]

 

提示:

  • 树中节点数目范围在 [0, 100]
  • -100 <= Node.val <= 100

Link - 题目链接

LeetCode - LeetCode-CN

Latest Accepted Submissions - 最近一次 AC 的提交

Language Runtime Memory Submission Time
javascript 80 ms 33 MB 2020/03/23 16:00
/**
 * 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) {
    return invert(root);
}

var invert = function(root) {
    if (!root) {
        return null;
    }

    var temp = null;
    if (root.left || root.right) { // 分支结点
        temp = root.left;
        root.left = root.right;
        root.right = temp;
        invert(root.left);
        invert(root.right);

        return root;
    } else { // 叶子结点
        return root;
    }
};

My Notes - 我的笔记

No notes