forked from zhuli19901106/leetcode-zhuli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclosest-binary-search-tree-value_1_AC.cpp
More file actions
48 lines (45 loc) · 1.03 KB
/
closest-binary-search-tree-value_1_AC.cpp
File metadata and controls
48 lines (45 loc) · 1.03 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
// Inorder traversal it is.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <cmath>
#include <stack>
using std::fabs;
using std::stack;
class Solution {
public:
int closestValue(TreeNode* root, double target) {
stack<TreeNode *> st;
TreeNode *p = root;
int res = root->val;
int val;
while (true) {
while (p != NULL) {
st.push(p);
p = p->left;
}
if (st.empty()) {
break;
}
p = st.top()->right;
val = st.top()->val;
st.pop();
if (fabs(val - target) < fabs(res - target)) {
res = val;
}
if (val >= target) {
break;
}
}
while (!st.empty()) {
st.pop();
}
return res;
}
};