FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/Week_02/id_131/LeetCode_783_131.cpp at master · feixiangcode/algorithm · GitHub
feixiangcode
/
algorithm
Public
forked from
algorithm001/algorithm
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
Week_02
/
id_131
/
LeetCode_783_131.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
48 lines (43 loc) · 1.19 KB
Breadcrumbs
algorithm
/
Week_02
/
id_131
/
LeetCode_783_131.cpp
Copy path
File metadata and controls
48 lines (43 loc) · 1.19 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
题目描述 :
* 给定一个二叉搜索树的根结点 root, 返回树中任意两节点的差的最小值。
*/
/*
*
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*
思路 :
* 既然是二叉搜索树,根据树的性质,知道root的右子树都是大于它的,左子树都是小于它的
* 那么如果做中序遍历,标准的做法是得到一个递增的序列
* 我们就先遍历右根,节点,左根,这样就会得到一个递减的序列。
* 然后对这个序列相邻相减,取最小值即可。 实现时,可以优化掉这个序列。
* 在遍历时记录上一个访问的节点值,和当前节点相减,记录下最小值即可。
* 这样就可以做到时间复杂度O(n)和空间复杂度O(1)
*/
class
Solution
{
int
pre
=
INT_MIN
;
int
minVal =
INT_MAX
;
public:
void
recycle
(TreeNode* root)
{
if
( root ==
NULL
)
return
;
recycle
(root->
left
);
if
(
INT_MIN
!=
pre
)
{
minVal = minVal < (root->
val
-
pre
) ? minVal : (root->
val
-
pre
);
}
pre
= root->
val
;
recycle
(root->
right
);
}
int
minDiffInBST
(TreeNode* root)
{
if
(
NULL
== root)
return
0
;
recycle
(root);
return
minVal;
}
};
Back
|
FazBrowse Home
|
New Git URL