226. Invert Binary Tree

翻轉二元樹,先暫存右邊,再將右邊定義左邊,再用剛暫存的定義右邊

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($val = 0, $left = null, $right = null) {
 *         $this->val = $val;
 *         $this->left = $left;
 *         $this->right = $right;
 *     }
 * }
 */
class Solution {

    private TreeNode $newTree;

    /**
     * @param TreeNode $root
     * @return TreeNode
     */
    function invertTree($root) {
        return $this->invert($root);   
    }

    function invert($root) {
        if ($root === null){
            return;
        }

        $temp = $root->right;
        $root->right = $this->invert($root->left);
        $root->left = $this->invert($temp);

        return $root;
    }
}

Last updated