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

D59 226. Invert Binary Tree

題目連接

226. Invert Binary Treephp

題目分析

反轉二叉樹。node

思路

相似反轉兩個變量,先把左右子樹存進單獨的變量,再相互覆蓋左右子樹。
並對子樹進行相同的操做。this

最終代碼

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

若以爲本文章對你有用,歡迎用愛發電資助。.net

相關文章
相關標籤/搜索