当前位置: 面试刷题>> 二叉树翻转 (经典算法题500道)


题目描述补充

题目:二叉树翻转

给定一棵二叉树,请编写一个函数来翻转这棵二叉树,即交换每个节点的左右子树。翻转后,原树的左子树变为右子树,原树的右子树变为左子树。

示例

输入的二叉树如下:

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

翻转后的二叉树应为:

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

PHP 示例代码

class TreeNode {
    public $val;
    public $left;
    public $right;

    function __construct($val = 0, $left = null, $right = null) {
        $this->val = $val;
        $this->left = $left;
        $this->right = $right;
    }
}

function invertTree($root) {
    if ($root === null) {
        return null;
    }
    
    // 交换当前节点的左右子树
    $temp = $root->left;
    $root->left = $root->right;
    $root->right = $temp;
    
    // 递归翻转左子树和右子树
    invertTree($root->left);
    invertTree($root->right);
    
    return $root;
}

Python 示例代码

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def invertTree(root):
    if root is None:
        return None
    
    # 交换当前节点的左右子树
    root.left, root.right = root.right, root.left
    
    # 递归翻转左子树和右子树
    invertTree(root.left)
    invertTree(root.right)
    
    return root

JavaScript 示例代码

function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}

function invertTree(root) {
    if (root === null) {
        return null;
    }
    
    // 交换当前节点的左右子树
    let temp = root.left;
    root.left = root.right;
    root.right = temp;
    
    // 递归翻转左子树和右子树
    invertTree(root.left);
    invertTree(root.right);
    
    return root;
}

码小课网站中有更多相关内容分享给大家学习,包括但不限于数据结构与算法、编程技巧、面试准备等,欢迎访问码小课网站获取更多学习资源。

推荐面试题