-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlowestCommonAncestorOfABinaryTree.php
More file actions
75 lines (51 loc) · 1.4 KB
/
lowestCommonAncestorOfABinaryTree.php
File metadata and controls
75 lines (51 loc) · 1.4 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
class TreeNode {
public $val = null;
public $left = null;
public $right = null;
function __construct($value) { $this->val = $value; }
}
class Solution {
public $result;
/**
* @param TreeNode $root
* @param TreeNode $p
* @param TreeNode $q
* @return TreeNode
*/
function lowestCommonAncestor($root, $p, $q) {
if($root === null){
return $this->result;
}
$this->dfs($root, $p, $q);
return $this->result;
}
function dfs($root, $p, $q)
{
if($root === null){
return 0;
}
//检查左子树含p/q个数
$leftContains = $this->dfs($root->left, $p, $q);
if($this->result !== null){
return 2;
}
//检查右子树含p/q个数
$rightContains = $this->dfs($root->right, $p, $q);
if($this->result !== null){
return 2;
}
$rootContains = 0;
//检查本身是否为p/q
if($root === $p || $root === $q){
$rootContains = 1;
}
if($rootContains === 1 && ($leftContains === 1 || $rightContains === 1)){
$this->result = $root;
}
if($rootContains === 0 && ($leftContains === 1 && $rightContains === 1)){
$this->result = $root;
}
return $leftContains + $rightContains + $rootContains;
}
}