Leetcode PHP题解--D59 226. Invert Binary Tree

D59 226. Invert Binary Tree

题目链接

226. Invert Binary Tree

题目分析

反转二叉树。

思路

类似反转两个变量,先把左右子树存进单独的变量,再相互覆盖左右子树。
并对子树进行相同的操作。

最终代码


<?php
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($value) { $this->val = $value; }
 * }
 */
class Solution {
    /**
     * @param TreeNode $root
     * @return TreeNode
     */
    function invertTree($root) {
        $left = $root->left;
        $right = $root->right;
        $root->left = $right;
        $root->right = $left;
        if($root->left){
            $this->invertTree($root->left);
        }
        
        if($root->right){
            $this->invertTree($root->right);
        }
        
        return $root;
    }
    
}

若觉得本文章对你有用,欢迎用爱发电资助。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容