Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Inorder Successor in BST - Tìm kế tiếp in-order trong BST (phiên bản 2)


Cho cây BST và nút p, tìm nút kế tiếp in-order (khóa nhỏ nhất lớn hơn p.val).

Ví dụ: root=[2,1,3], p=1 → 2.

Giải thuật (Đệ quy BST)

Tương tự bài trước: nếu root.val <= p.val tìm bên phải, ngược lại thử tìm bên trái, không có thì trả root.

Cài đặt C++

#include <bits/stdc++.h>
using namespace std;

class TreeNode {
public:
    int val;
    TreeNode *left, *right;
    TreeNode(int data) { val = data; left = right = NULL; }
};

class Solution {
public:
    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
        if (!root) return NULL;
        if (root->val <= p->val)
            return inorderSuccessor(root->right, p);
        else {
            TreeNode* option = inorderSuccessor(root->left, p);
            return !option ? root : option;
        }
    }
};

int main() {
    TreeNode* root = new TreeNode(2);
    root->left = new TreeNode(1);
    root->right = new TreeNode(3);
    TreeNode* p = root->left;
    Solution ob;
    cout << ob.inorderSuccessor(root, p)->val;
    return 0;
}

Đầu vào

{2,1,3},1

Đầu ra

2