-
530.二叉搜索树的最小绝对差
-
class Solution { public: int ret=100000; TreeNode* cur=NULL; void solve(TreeNode* node){ if(node==NULL) return ; solve(node->left); if(cur!=NULL){ if(ret>abs(cur->val-node->val)) ret=abs(cur->val-node->val);} cur=node; solve(node->right); } int getMinimumDifference(TreeNode* root) { solve(root); return ret; } };
-
501.二叉搜索树中的众数
-
class Solution { public: vector<int> ret; int count = 0; int max = 0; TreeNode* cur = NULL; void solve(TreeNode* node) { if (node == NULL) return; solve(node->left); if (cur == NULL) count = 1; else if (cur->val == node->val) count++; else count = 1; if (count == max) ret.push_back(node->val); if (count > max) { max = count; ret.clear(); ret.push_back(node->val); } cur = node; solve(node->right); return; } vector<int> findMode(TreeNode* root) { solve(root); return ret; } };
-
236. 二叉树的最近公共祖先
-
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root == NULL) return root; if (root == p || root == q) return root; TreeNode* left = lowestCommonAncestor(root->left, p, q); TreeNode* right = lowestCommonAncestor(root->right, p, q); if (left != NULL && right != NULL) return root; if (left == NULL && right != NULL) { return right; } else if (left != NULL && right == NULL) return left; else return NULL; } };