Problem
Write an algorithm to find the “next” node (i.e., in-order successor) of a given node in a binary search tree.
Return null if there’s no “next” node for the given node.
Example1
Example2
Solution
注意参数是引用
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
TreeNode * prev = NULL;
TreeNode * ret = NULL;
inorder(root,p,prev,ret);
return ret;
}
//注意prev和ret都是指针的引用
void inorder(TreeNode* root, TreeNode* p,TreeNode* &prev,TreeNode* &ret)
{
if(!root)
return;
inorder(root->left,p,prev,ret);
if(prev)
{
if(prev == p)
ret = root;
}
prev = root;
inorder(root->right,p,prev,ret);
}
};