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

    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?

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void treeWalk(TreeNode *root, TreeNode *&prv, TreeNode *&first, TreeNode *&second)
        {
          if(root)
          {
              treeWalk(root->left,prv,first,second);
              if((prv!=NULL)&&(prv->val>root->val))
              {
                  if(first==NULL) first=prv;
                  second=root;
              }
              prv=root;
              treeWalk(root->right,prv,first,second);
          }
        }
        void recoverTree(TreeNode *root) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            TreeNode* first=NULL;
            TreeNode* second=NULL;
            TreeNode* prv=NULL;
            treeWalk(root,prv,first,second);
            swap(first->val,second->val);
        }
    };
    

      

  • 相关阅读:
    如何处理数集据不平衡的问题
    xgb&lgb&ctb区别
    LDA与gibbs采样
    撸了一个 Feign 增强包
    行为驱动模型-Behave
    MySQL 主从复制常见错误答疑
    POJ 1191
    POJ 1141
    HDU 1754
    POJ 3468
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3471215.html
Copyright © 2011-2022 走看看