101. Symmetric 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 {

    /**
     * @param TreeNode $root
     * @return Boolean
     */
    function isSymmetric($root) {
        if ($root === null) {
            return true;
        }

        return $this->isNodesMirror($root->left, $root->right);
    }

    private function isNodesMirror($left, $right) {
        if ($left === null && $right === null) {
            return true;
        }

        if ($left === null || $right === null) {
            return false;
        }
        // 左右節點交叉比對
        return $left->val === $right->val
         && $this->isNodesMirror($left->right, $right->left)
         && $this->isNodesMirror($left->left, $right->right);
    }
}

Last updated