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

D59 226. Invert Binary Tree

题目链接

226. Invert Binary Tree

题目分析

反转二叉树。

思路

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

最终代码


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

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

你可能感兴趣的:(算法leetcodephp)