题解 | #牛牛的二叉树问题#
牛牛的二叉树问题
https://www.nowcoder.com/practice/1b80046da95841a9b648b10f1106b04e
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param target double浮点型
* @param m int整型
* @return int整型vector
*/
vector<int> findClosestElements(TreeNode* root, double target, int m)
{
// write code here
vector<int> ans;
if (root == NULL)
{
return ans;
}
vector<pair<double,int>> diffValue;
//采用深度优先搜索
stack<TreeNode* > st;
st.push(root);
while(!st.empty())
{
TreeNode* Node = st.top();
st.pop();
if (Node != NULL)
{
if (Node->right != NULL)
{
st.push(Node->right);
}
if (Node->left != NULL)
{
st.push(Node->left);
}
st.push(Node);
st.push(NULL);
}
else
{
Node = st.top();
st.pop();
diffValue.emplace_back(abs(Node->val - target),Node->val);
}
}
sort(diffValue.begin(),diffValue.end(),[](const pair<double,int> a,const pair<double,int> b)
{
return a.first < b.first;
});
// for (auto it : diffValue)
// {
// cout << it.second << " " << it.first << endl;
// }
for (int i = 0; i < m;++i)
{
ans.push_back(diffValue[i].second);
}
sort(ans.begin(),ans.end());
return ans;
}
};
