-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path235.二叉搜索树的最近公共祖先.go
123 lines (112 loc) · 2.5 KB
/
235.二叉搜索树的最近公共祖先.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*
* @lc app=leetcode.cn id=235 lang=golang
*
* [235] 二叉搜索树的最近公共祖先
*
* https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
*
* algorithms
* Easy (59.02%)
* Likes: 109
* Dislikes: 0
* Total Accepted: 13.9K
* Total Submissions: 23.5K
* Testcase Example: '[6,2,8,0,4,7,9,null,null,3,5]\n2\n8'
*
* 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
*
* 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x
* 的深度尽可能大(一个节点也可以是它自己的祖先)。”
*
* 例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
*
*
*
*
*
* 示例 1:
*
* 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
* 输出: 6
* 解释: 节点 2 和节点 8 的最近公共祖先是 6。
*
*
* 示例 2:
*
* 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
* 输出: 2
* 解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。
*
*
*
* 说明:
*
*
* 所有节点的值都是唯一的。
* p、q 为不同节点且均存在于给定的二叉搜索树中。
*
*
*/
/**
* Definition for TreeNode.
* type TreeNode struct {
* Val int
* Left *ListNode
* Right *ListNode
* }
*/
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
sp := NewStack()
PreOrder(root, p, sp)
sq := NewStack()
PreOrder(root, q, sq)
pPaths := sp.Values()
qPaths := sq.Values()
i, j := 0, 0
for i < len(pPaths) && j < len(qPaths) {
if pPaths[i] == qPaths[j] {
i++
j++
} else {
break
}
}
return pPaths[i-1]
}
func PreOrder(node, expect *TreeNode, s *Stack) {
if node != nil {
s.Push(node)
PreOrder(node.Left, expect, s)
PreOrder(node.Right, expect, s)
if s.Size() > 0 && s.Top() != expect {
s.Pop()
}
}
}
type Stack struct {
elements []*TreeNode
}
func NewStack() *Stack {
return &Stack{
elements: make([]*TreeNode, 0),
}
}
func (s *Stack) Size() int {
return len(s.elements)
}
func (s *Stack) Push(node *TreeNode) {
s.elements = append(s.elements, node)
}
func (s *Stack) Pop() *TreeNode {
size := s.Size()
val := s.elements[size-1]
s.elements = s.elements[:size-1]
return val
}
func (s *Stack) Top() *TreeNode {
size := s.Size()
return s.elements[size-1]
}
func (s *Stack) Values() []*TreeNode {
return s.elements
}