CONNLY-J / cultivate

0 stars 0 forks source link

226翻转二叉树,https://leetcode-cn.com/problems/invert-binary-tree/ #14

Open CONNLY-J opened 4 years ago

CONNLY-J commented 4 years ago
/**
 * 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 === null){
        return null
    }
    var temp = root.right;
    root.right = root.left;
    root.left = temp;
    invertTree(root.left);
    invertTree(root.right);

    return root;
};

解题思路:若根为空则返回空; 交换当前节点的左右子树; 再递归交换当前节点的左子树及右子树