LeetCode OJ - 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?

分析:1、中序遍歷生成序列,找出無序元素。 2、遞歸記錄兩個無序元素,最後交換

        首先看一個升序數組中,若兩個數被錯誤交換了,如何處理:

#include <iostream>
#include <vector>
#include <stack>
#include <map>
#include <queue>
#include <set>	
#include <stdio.h>
using namespace std;

int node1 = INT_MIN;
int node2 = INT_MIN;

void DFS(int *A, int n) {
    for(int i = 0; i < n - 1; i++) {
		if(A[i] > A[i+1]) {
			if(node1 == INT_MIN) {
			    node1 = i;
				node2 = i + 1;
			} else {
			    node2 = i + 1;
			}
		}
	}
	int tmp = A[node1];
    A[node1] = A[node2];
	A[node2] = tmp;
}

int main(int argc, char* argv[])
{
    int A[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 26, 13, 14, 12};
	int n = sizeof(A) / sizeof(int);
	DFS(A, n);

	for(int i = 0; i < n; i++) {
	    cout << A[i] << " ";
	}
	cout << endl;
	return 0;
}



中序遍歷相當於依次訪問left、root、right,而pre依次記錄的子訪問的前一個節點。如同pre1與root1比較,若pre1 > root1則表明pre1爲問題節點;若pre2 > root2則root2爲問題節點。記錄這兩個節點並交換。

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章