美文网首页Leetcode题解-PHP版
Leetcode PHP题解--D59 226. Invert

Leetcode PHP题解--D59 226. Invert

作者: skys215 | 来源:发表于2019-05-13 08:25 被阅读0次

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题解--D59 226. Invert

    本文链接:https://www.haomeiwen.com/subject/abpkaqtx.html