285. Inorder Successor in BST

Problem

Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

Note: If the given node has no in-order successor in the tree, return null.

Solution

用中序遍歷的方式遍歷樹,這里這個節(jié)點的位置有幾種可能性:

  1. 節(jié)點有右孩子:那么找到右孩子的最左邊的子孫。如果沒有子孫,那么就是右孩子本身。
  2. 節(jié)點沒有右孩子:那么找到最close的上層父親,并且這個節(jié)點是這個父親左子樹的一員。

如果無法滿足上述情況,那么就沒有successor。另外,這里有幾個corner case,比如p == root,并且root沒有右孩子。比如,節(jié)點在node的右子樹中,如果node != root,返回p,如果node == root,返回null。

/**
* 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 *find(TreeNode *root, TreeNode *p, TreeNode *treeRoot) {
        if (root == NULL) {
            return NULL;
        }
        TreeNode *left = find(root->left, p, treeRoot);
        if (left != p && left != NULL) {
            return left;
        } else if (p == left) {
            return root;
        }
        if (p == root) {
            TreeNode *node = p->right;
            TreeNode *preNode = NULL;
            while (node) {
                preNode = node;
                node = node->left;
            }
            if (preNode) {
                return preNode;
            } else {
                return root == treeRoot ? NULL : p;
            }
        }
        TreeNode *right = find(root->right, p, treeRoot);
    
        if (right != p && right != NULL) {
            return right;
        } else if (right == p) {
            if (root == treeRoot) {
                return NULL;
            } else {
                return p;
            }
        }
    
        return NULL;
    }

    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
        return find(root, p, root);
    }
};
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,936評論 0 33
  • 原題 Given a binary search tree and a node in it, find the ...
    Jason_Yuan閱讀 2,498評論 1 2
  • 總結類型: 完全子樹(#222) BST(左右子樹值的性質(zhì),注意不僅要滿足parent-child relatio...
    __小赤佬__閱讀 783評論 0 0
  • 目錄 簡書的 markdown 都不支持 [TOC] 語法……我就不貼目錄了。下面按照類別,列出了29道關于二叉樹...
    被稱為L的男人閱讀 3,460評論 0 8
  • 最近在和朋友聊天的時候說到一個問題,就是關于我可憐的表達能力。 想了想也是,有多少想說的話浮現(xiàn)在腦海,最終卻濃縮成...
    Reyfe閱讀 131評論 0 0

友情鏈接更多精彩內(nèi)容