Friday, May 13, 2022

[LeetCode] 226. Invert Binary Tree

     

"踏上LeetCode解題之路,順手紀錄一下PHP練功的過程囉。這是第十八篇~~"


Invert Binary Tree - LeetCode


思考過程

待補上


結果

/**
 * 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 {

    /**
     * @param TreeNode $root
     * @return TreeNode
     */

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

        if ($node->left !== null) {
            $this->invertTree($node->left);
        }

        if ($node->right !== null) {
            $this->invertTree($node->right);
        }

        $temp = $node->right;
        $node->right = $node->left;
        $node->left = $temp;
        return $node;
    }
}

Contact Form

Name

Email *

Message *