leetcode 99. Recover Binary Search Tree

相关问题

144. Binary Tree Preorder Traversal
94. Binary Tree Inorder Traversal
145. Binary Tree Postorder Traversal

99. Recover Binary Search Tree

Discription

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?

思路

中序遍历。
二叉平衡树的中序遍历结果是个有序数组。
交换两个元素的结果有两种情况,以12345为例:

  1. 交换相邻的两个元素,如(3,4),得到12435。此时数组中包含一个逆序对(4,3),交换该逆序对即可;
  2. 交换不相邻的两个元素,如(1,5),得到52341。此时数组中包含两个逆序对(5,2),(4,1),将第一个逆序对的第一个元素与第二个逆序对的第二个元素交换即可;

时间复杂度: O(n)
空间复杂度: O(h) ,h为树高

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void recoverTree(TreeNode* root) {
        vector sta;
        if (root) sta.push_back(root);

        TreeNode *p, *q, *preVisted = new TreeNode(INT_MIN);
        bool first = true;   

        while(!sta.empty())
        {
            while(sta.back())
            {
                sta.push_back(sta.back()->left);
            }

            sta.pop_back();

            if (!sta.empty())
            {
                TreeNode *pNode = sta.back();
                sta.pop_back();

                // 寻找逆序对
                if (preVisted->val > pNode->val)
                {
                    if (first)
                    {
                        p = preVisted;
                        q = pNode;
                        first = false;
                    }else
                    {
                        q = pNode;
                        break;
                    }
                }

                preVisted = pNode;
                sta.push_back(pNode->right);
            }
        }

        // 交换元素
        int tmp = q->val;
        q->val = p->val;
        p->val = tmp;
    }
};

扩展

题目要求 O(1) 空间复杂度。

你可能感兴趣的:(leetcode,二叉树,深度优先搜索)