100.same-tree

Description:

Given the roots of two binary trees p and q, 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
2
3
4
5
6
Input: p = [1,2,3], q = [1,2,3]
1 1
/ \ / \
2 3 2 3

Output: true
1
2
3
4
5
6
Input: p = [1,2], q = [1,null,2]
1 1
/ \
2 2

Output: false
1
2
3
4
5
6
Input: p = [1,2,1], q = [1,1,2]
1 1
/ \ / \
2 1 1 2

Output: false

First Answer (Recursive):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php

namespace LeetCode\SameTree;

/**
* 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
{
/**
* @var bool $answer
*/
protected $answer = true;
/**
* @param TreeNode $p
* @param TreeNode $q
* @return bool
*/
public function isSameTree($p, $q)
{
$this->findAnswer($p, $q);
return $this->answer;
}

/**
* @param TreeNode $p
* @param TreeNode $q
*/
private function findAnswer($p, $q)
{
if ($p->val !== $q->val) {
return $this->answer = false;
}

if (($p->left->val !== $q->left->val) || ($p->right->val !== $q->right->val)) {
return $this->answer = false;
}

if (!is_null($p->left) && !is_null($q->left)) {
$this->findAnswer($p->left, $q->left);
}

if (!is_null($p->right) && !is_null($q->right)) {
$this->findAnswer($p->right, $q->right);
}
}
}
  • Time Complexity: O(n)

ʕ •ᴥ•ʔ:很久沒寫文了,最近覺得情況不算太好。
重新努力,用寫文把狀態找回來。