Solution1:我的答案
对中序遍历的结果查找之~
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Successor {
public:
int findSucc(TreeNode* root, int p) { //中序遍历 或者 分类讨论
// write code here
return my_find(root, p);
}
void Inorder_travel(TreeNode* root, vector<int> &vec_val) {
if(root == NULL)
return;
if(root->left != NULL)
Inorder_travel(root->left, vec_val);
vec_val.push_back(root->val);
if(root->right != NULL)
Inorder_travel(root->right, vec_val);
}
int my_find(TreeNode* root, int p) {
vector<int> temp;
Inorder_travel(root, temp);
for(int i = 0; i < temp.size() - 1; i++) {
if(temp[i] == p)
return temp[i+1];
}
return -1;
}
};
Solution2:
参考网址:https://www.nowcoder.com/profile/1465900/codeBookDetail?submissionId=13160118
要寻找中序遍历的某个节点的下一个节点,肯定是要通过中序遍历实现的,题目中明确告诉我们节点的值没有重复,所以只要在中序遍历的过程中,某个节点的值等于p,则告诉递归者下一个要遍历的节点便是我们要找的节点,这个需要有个信号在多次递归之间进行传递消息,c++里用引用完全可以实现,只需要传递一个bool类型的引用便可。
class Successor {
public:
int findSucc(TreeNode* root, int p) {
// write code here
bool sign=0;
return findSucc1(root,p,sign);
}
int findSucc1(TreeNode* root, int p, bool &sign) {
if (!root)
return -1;
int left = findSucc1(root->left, p, sign);
if (left != -1)
return left;
if (sign == true)
return root->val;
if (root->val == p)
sign = true;
return findSucc1(root->right, p, sign);
}
};
节省了大量空间!