面试题 04.06. Successor LCCI

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);
    }
};
发布了496 篇原创文章 · 获赞 215 · 访问量 53万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/104703090