Skip to content

Latest commit

 

History

History
71 lines (55 loc) · 1.41 KB

are_two_trees_the_same.md

File metadata and controls

71 lines (55 loc) · 1.41 KB

Are the two trees the same

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1: Input: 1 1 / \ /
2 3 2 3

    [1,2,3],   [1,2,3]

Output: true

Example 2: Input: 1 1 /
2 2

    [1,2],     [1,null,2]

Output: false

Example 3: Input: 1 1 / \ /
2 1 1 2

    [1,2,1],   [1,1,2]

Output: false

/**
 * 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 $p
     * @param TreeNode $q
     * @return Boolean
     */
    function isSameTree($p, $q) {
        if ($p->val === null && $q->val === null) {
            return true;
        }

        if ($p->val === null || $q->val === null) {
            return false;
        }

        if ($p->val !== $q->val) {
            return false;
        }

        return $this->isSameTree($p->left, $q->left) && $this->isSameTree($p->right, $q->right);
    }
}