iterative O(h) time O(1) space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class Solution { public: int closestValue(TreeNode* root, double target) { int res = root->val; while (root) { if (fabs(root->val - target) < fabs(res - target)) { res = root->val; } root = root->val > target ? root->left : root->right; } return res; } };
|
recursive O(h) time O(1) space
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
|
class Solution { public: int closestValue(TreeNode* root, double target) { res = root->val; dfs(root, target); return res; }
void dfs(TreeNode *root, double target) { if (!root) return; if (fabs(root->val - target) < fabs(res - target)) { res = root->val; } root->val > target ? dfs(root->left, target) : dfs(root->right, target); }
int res; };
|
O(n) time O(h) space
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
|
class Solution { public: int closestValue(TreeNode* root, double target) { res = root->val; dfs(root, target); return res; }
void dfs(TreeNode *root, double target) { if (!root) return; if (fabs(root->val - target) < fabs(res - target)) { res = root->val; } dfs(root->left, target); dfs(root->right, target); }
int res; };
|