lintcode 448. 二叉查找樹的中序後繼

本來以爲  既然都是找後繼 都是一樣的

結果 都!不!一!樣!

查找的時候怎麼用val比較呢?

考慮如果當前root的值比查找的 小於或等於:淘汰掉左子樹就好

要是需要找到左子樹了,那麼遞歸下去同樣的方法,如果找不到,那麼說明當前這個根節點是要找的

class Solution {
public:
    /*
     * @param root: The root of the BST.
     * @param p: You need find the successor node of p.
     * @return: Successor of p.
     */
    TreeNode * inorderSuccessor(TreeNode * root, TreeNode * p) {
        if (root == NULL) return NULL;
        if (root->val <= p->val) {
            return inorderSuccessor(root->right, p);
        } else {
            TreeNode* left = inorderSuccessor(root->left, p);
            return left?left:root;
        }
    }
};

個人喜歡這個非遞歸的 ,先根據p的val找到等於val的節點

然後,根據next的性質,那麼是父節點,那麼是右左左左左

父節點在上次找=val的時候找到的更新

class Solution {
public:
    /*
     * @param root: The root of the BST.
     * @param p: You need find the successor node of p.
     * @return: Successor of p.
     */
    TreeNode * inorderSuccessor(TreeNode * root, TreeNode * p) {
        if (root == NULL) return NULL;
        TreeNode* fa = NULL;
        while(root && root->val != p->val) {
            if(root->val < p->val) root = root->right;
            else if (root->val > p->val) {
                fa = root;
                root = root->left;
            }
        }
        TreeNode* current = root;
        if(root == NULL) return NULL;
        if(root->right == NULL) return fa;
        else {
            root = root->right;
            while(root->left) root= root->left;
            return root;
        }
    }
};

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章