# 【重点】程序员面试金典——4.6寻找下一个结点

## 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:

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);
}
};