码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-99-Recover Binary Search Tree

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

标签:div   example   pac   leetcode   code   算法   struct   nod   out   

算法描述:

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

标签:div   example   pac   leetcode   code   算法   struct   nod   out   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!