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;
    }

}

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


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Leetcode PHP题解--D58 693. Binary Number with Alternating Bits

>> 下一篇: Leetcode基础刷题之PHP解析(2. Add Two Numbers)