首页 > 其他 > 详细

LeetCode-99-Recover Binary Search Tree

时间:2019-02-15 19:50:11      阅读:156      评论:0      收藏:0      [点我收藏+]

算法描述:

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

Recover the tree without changing its structure.

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
     2

Output: [3,1,null,null,2]

   3
  /
 1
     2

Example 2:

Input: [3,1,4,null,null,2]

  3
 / 1   4
   /
  2

Output: [2,1,4,null,null,3]

  2
 / 1   4
   /
  3

Follow up:

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

解题思路:二叉搜索树的中序遍历是从小到大的顺序。所以,中序遍历该树,并将破坏顺序的两个节点值交换。

void recoverTree(TreeNode* root) {
        if(root == nullptr ) return;
        TreeNode* first = nullptr;
        TreeNode* second = nullptr;
        TreeNode* prev = nullptr;
        stack<TreeNode*> stk; 
        TreeNode* cur = root;
        while(cur!=nullptr || !stk.empty()){
            while(cur!=nullptr){
                stk.push(cur);
                cur=cur->left;
            }
                        
            TreeNode* temp = stk.top();
            stk.pop();
            if(prev!=nullptr && prev->val > temp->val){
                if(first==nullptr) first = prev;
                second = temp;
            }
            prev= temp;
            if(temp->right!=nullptr) cur=temp->right;
        }
        int val = first->val;
        first->val = second->val;
        second->val = val;
    }

 

LeetCode-99-Recover Binary Search Tree

原文:https://www.cnblogs.com/nobodywang/p/10385482.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!