LeetCode //C - 99. Recover Binary Search Tree

99. Recover Binary Search Tree

You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
 

Example 1:

在这里插入图片描述

Input: root = [1,3,null,null,2]
Output: [3,1,null,null,2]
Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.

Example 2:

在这里插入图片描述

Input: root = [3,1,4,null,null,2]
Output: [2,1,4,null,null,3]
Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.

Constraints:
  • The number of nodes in the tree is in the range [2, 1000].
  • − 2 31 < = N o d e . v a l < = 2 31 − 1 -2^{31} <= Node.val <= 2^{31} - 1 231<=Node.val<=2311

From: LeetCode
Link: 99. Recover Binary Search Tree


Solution:

Ideas:
  1. inorderTraversal function performs an in-order traversal of the tree, keeping track of the previous node (prev). It identifies the first and second nodes that are out of order (first and second).
  2. recoverTree function calls inorderTraversal to identify the two nodes and then swaps their values.
  3. newTreeNode are helper functions for creating and printing the tree, respectively.
Code:
void inorderTraversal(struct TreeNode* root, struct TreeNode** prev, struct TreeNode** first, struct TreeNode** second) {
    if (root == NULL) return;
    
    // Traverse left subtree
    inorderTraversal(root->left, prev, first, second);
    
    // Process current node
    if (*prev && (*prev)->val > root->val) {
        if (*first == NULL) {
            *first = *prev;
        }
        *second = root;
    }
    *prev = root;
    
    // Traverse right subtree
    inorderTraversal(root->right, prev, first, second);
}

void recoverTree(struct TreeNode* root) {
    struct TreeNode *prev = NULL, *first = NULL, *second = NULL;
    
    // Perform in-order traversal to find the two nodes
    inorderTraversal(root, &prev, &first, &second);
    
    // Swap the values of the two nodes
    if (first && second) {
        int temp = first->val;
        first->val = second->val;
        second->val = temp;
    }
}

// Helper function to create a new tree node
struct TreeNode* newTreeNode(int val) {
    struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    node->val = val;
    node->left = NULL;
    node->right = NULL;
    return node;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值