代码随想录算法训练营第十八天| 530.二叉搜索树的最小绝对差 501.二叉搜索树中的众数 236. 二叉树的最近公共祖先

530.二叉搜索树的最小绝对差

思路:

根据二叉搜素树的特点,直接中序遍历,就是有序数组,然后两个节点进行比较,就可以

代码:

 1 int getMinimumDifference(TreeNode* root) {
 2     if(!root) return 0;
 3     int result = INT_MAX;
 4     multiset<int> vals;
 5     stack<TreeNode*> selected;
 6     selected.push(root);
 7     while (!selected.empty())
 8     {
 9         auto cur_ = selected.top(); selected.pop();
10         vals.insert(cur_->val);
11 
12         if (cur_->left) selected.push(cur_->left);
13         if (cur_->right) selected.push(cur_->right);
14     }
15 
16     for (auto i = vals.begin(); i != --vals.end(); i++)
17     {
18         auto j = next(i);
19         if (abs(*i - *j) < result) {
20             result = abs(*i - *j);
21         }
22     }
23 
24     return result;
25 }

   501.二叉搜索树中的众数

搜索树的思路

用两个指针,一个指向前一个,如果当前和前一个相等,就+1,如果不等就-1

思路:

用map找出来最大的值,然后如果不是,就去掉

代码

 1 vector<int> findMode(TreeNode* root) 
 2 {
 3     vector<int> result;
 4     if (!root)return result;
 5 
 6     map<int, int> valCount;
 7     stack<TreeNode*> selected;
 8     selected.push(root);
 9     while (!selected.empty())
10     {
11         auto cur_ = selected.top();
12         if (cur_->left)
13         {
14             selected.push(cur_->left);
15 
16             cur_->left = NULL;
17         }
18         else
19         {
20             selected.pop();
21             if (valCount.find(cur_->val) == valCount.end())
22             {
23                 valCount.insert(make_pair(cur_->val, 0));
24             }
25             valCount[cur_->val]++;
26 
27             if (cur_->right)
28             {
29                 selected.push(cur_->right);
30             }
31         }
32     }
33 
34     int max_ = INT_MIN;
35     for (auto pair_ : valCount)
36     {
37         if (max_ < pair_.second)
38         {
39             max_ = pair_.second;
40         }
41     }
42 
43 
44     auto it_ = valCount.begin();
45     while (it_ != valCount.end())
46     {
47         if (max_ == it_->second)
48         {
49             result.push_back(it_->first);
50 
51         }
52         ++it_;
53     }
54 
55     return result;
56 }

 236. 二叉树的最近公共祖先 

思路:

后序遍历,找到节点,然后返回,如果它的左右节点都是,那么就返回当前节点,如果左节点有,那么返回左节点,如果右节点有,那么返回右节点

代码:

 1 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
 2     if (!root) return NULL;
 3     if (root == p || root == q) return root;
 4 
 5     TreeNode* right = NULL, * left = NULL;
 6     if (root->left) left = lowestCommonAncestor(root->left, p, q);
 7 
 8     if (root->right)right = lowestCommonAncestor(root->right, p, q);
 9 
10     if (left && right) return root;
11     else if (left && !right) return left;
12     else if (!left && right) return right;
13     else return NULL;
14 }

 

posted @ 2023-06-27 11:12  博二爷  阅读(3)  评论(0编辑  收藏  举报