zoukankan      html  css  js  c++  java
  • Recover Binary Search Tree [LeetCode]

    Two elements of a binary search tree (BST) are swapped by mistake.

    Recover the tree without changing its structure.

    Note:
    A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

    Sulotion: Considers a BST as a storted array, so we can traverse the BST inorderly just like iterate the ascending sequence. In this way, we can easily find two elements swapped by mistake, then swaps them back.

     1    void inorder(TreeNode * root, TreeNode ** error_node, TreeNode ** pre_node, int * is_swap){
     2         if( root == NULL )
     3             return;
     4         if(root->left != NULL)
     5             inorder(root -> left, error_node, pre_node, is_swap);
     6         
     7         if((*pre_node) != NULL) {
     8             if ((*pre_node)->val > root->val){
     9                 if ((*error_node) == NULL)
    10                     *error_node = *pre_node;
    11             }else if( (*error_node) != NULL && (*error_node)->val < root->val && (*error_node)->val > (*pre_node )->val){
    12                 //swap error node and pre node
    13                 int tmp = (*error_node)->val;
    14                 (*error_node )->val = (*pre_node)->val;
    15                 (*pre_node)->val = tmp;
    16                 *is_swap = 1;
    17                 return;
    18              }
    19         }
    20         
    21         (*pre_node )= root;   
    22         
    23         if( root -> right != NULL)
    24             inorder(root -> right, error_node, pre_node, is_swap);
    25     }
    26     
    27     void recoverTree(TreeNode *root) {
    28         // Note: The Solution object is instantiated only once and is reused by each test case.
    29         TreeNode * error_node = NULL;
    30         TreeNode * pre_node = NULL;
    31         int is_swap = 0;
    32         inorder(root, &error_node, &pre_node, &is_swap);
    33         if ( is_swap == 0 && error_node != NULL){
    34             int tmp = error_node -> val;
    35             error_node -> val = pre_node -> val;
    36             pre_node -> val = tmp;
    37         }
    38     }
  • 相关阅读:
    Mac 10.12安装Atom文本增强编辑工具
    Mac 10.12安装SecureCRT
    Mac 10.12安装WebStorm
    Mac 10.12安装Command+Q误按提示工具
    Mac 10.12安装FTP工具FileZilla
    Mac 10.12安装VirtualBox
    Mac 10.12安装数据库管理工具MySQL Workbench
    Mac 10.12安装Homebrew图形化界面管理工具Cakebrew
    Mac 10.12安装图片切换工具ArcSoft Photo+
    Mac 10.12安装Git管理工具SourceTree
  • 原文地址:https://www.cnblogs.com/guyufei/p/3435683.html
Copyright © 2011-2022 走看看