LeetCode099 Recover Binary Search Tree

详细见:leetcode.com/problems/recover-binary-search-tree


Java Solution: github

package leetcode;

import java.util.ArrayList;

/*
 * 	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?
 */

import tools.TreeNode辅助.TreeNode;

public class P099_RecoverBinarySearchTree {
	static int N = Integer.MIN_VALUE;

	public static void main(String[] args) {
		TreeNode root = tools.TreeNode辅助.A_生成满二叉树(new int[] {
//				1,
//				N,3,
//				N,N,N,2
				10,
				5, 15, 
				N, N, 7, 20 
		});
		tools.TreeNode辅助.B_按层打印(root);
		new Solution().recoverTree(root);
		tools.TreeNode辅助.B_按层打印(root);
	}
	/*
	 * 	这样的AC,有点挫
	 * 	192 ms
	 */
	static class Solution {
		ArrayList<TreeNode> arr = new ArrayList<TreeNode>();
		boolean isFalse = false;
		public void recoverTree(TreeNode root) {
			searchAllTreeNode(root);
			for (int i = 0; i < arr.size(); i++) {
				for (int j = i + 1; j < arr.size(); j++) {
					TreeNode tree1 = arr.get(i);
					TreeNode tree2 = arr.get(j);
					if (tree1 == tree2) {
						continue;
					}
					int temp = tree1.val;
					tree1.val = tree2.val;
					tree2.val = temp;
					isFalse = false;
					search_judge(root, Long.MAX_VALUE, Long.MIN_VALUE);
					if (!isFalse) {
						return;
					}
					temp = tree1.val;
					tree1.val = tree2.val;
					tree2.val = temp;
				}
			}
		}
		private void searchAllTreeNode(TreeNode root) {
			if (root == null) {
				return;
			}
			arr.add(root);
			if (root.right != null) {
				searchAllTreeNode(root.right);
			}
			if (root.left != null) {
				searchAllTreeNode(root.left);
			}
		}
		void search_judge(TreeNode root, long max_edge, long min_edge) {
			if (isFalse) {
				return;
			}
			if ((long) root.val >= max_edge || (long) root.val <= min_edge) {
				isFalse = true;
				return;
			}
			if (root.left != null) {
				search_judge(root.left, root.val, min_edge);
			}
			if (root.right != null) {
				search_judge(root.right, max_edge, root.val);
			}
		}
	}
}


C Solution: github

/*
    url: leetcode.com/problems/recover-binary-search-tree
    both: AC 12ms 100.00%
*/

#include <stdio.h>
#include <stdlib.h>

typedef struct TreeNode stn;
typedef struct TreeNode * ptn;

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

typedef ptn T;
typedef struct al sal;
typedef struct al * pal;

struct al {
    int capacity;
    int size;
    T* arr;
};

pal al_init(int capacity) {
    pal l = (pal) malloc(sizeof(sal));
    if (capacity < 1) return NULL;
    l->arr = (T*) malloc(sizeof(T) * capacity);
    l->capacity = capacity;
    l->size = 0;
    return l;
}

void al_expand_capacity(pal l) {
    T* new_arr = (T*) malloc(sizeof(T) * (l->capacity * 2 + 1));
    int i = 0;
    for (i = 0; i < l->capacity; i ++)
        new_arr[i] = l->arr[i];
    free(l->arr);
    l->arr = new_arr;
    l->capacity = l->capacity * 2 + 1;
}

void al_add_last(pal l, T v) {
    if (l->capacity == l->size) al_expand_capacity(l);
    l->arr[l->size] = v;
    l->size ++;
}

T* al_convert_to_array_free_l(pal l) {
    T* arr = l->arr;
    free(l);
    return arr;
}

void pre_order(pal l, ptn root) {
    if (root == NULL) return;
    pre_order(l, root->left);
    al_add_last(l, root);
    pre_order(l, root->right);
}

void swap(int* a, int* b) {
    int t = *a;
    *a = *b;
    *b = t;
}

void recoverTree_n(ptn root) {
    int i = 0, c = 0;
    pal l = al_init(16);
    int w1 = 0, w2 = 0;
    int size = 0;
    ptn * arr = NULL;
    pre_order(l, root);
    size = l->size;
    arr = al_convert_to_array_free_l(l);
    for (i = 1; i < size; i ++) {
        if (arr[i]->val < arr[i-1]->val) {
            if (c == 0) {
                w1 = i;
                c ++;
            } else if (c == 1) {
                w2 = i;
                c ++;
            }
        }
    }
    if (c == 2) {
        swap(&(arr[w1-1]->val), &(arr[w2]->val));
    }
    if (c == 1) {
        swap(&(arr[w1]->val), &(arr[w1-1]->val));
    }
}

void pre_order_1(ptn root, ptn* p, ptn* ps) {
    if (root == NULL) return;
    pre_order_1(root->left, p, ps);
    if (*p != NULL)
    if (root->val <= (*p)->val) {
        if (ps[0] == NULL) {
            ps[0] = *p;
        }
        ps[1] = root;
    }
    *p = root;
    pre_order_1(root->right, p, ps);
}

void recoverTree_1(ptn root) {
    ptn p = NULL;
    ptn ps[2] = {NULL, NULL};
    pre_order_1(root, &p, ps);
    swap(&(ps[0]->val), &(ps[1]->val));
}

void recoverTree(ptn root) {
    recoverTree_n(root);
}




Python Solution: github

#coding=utf-8

'''
    url: leetcode.com/problems/recover-binary-search-tree
    @author:     zxwtry
    @email:      zxwtry@qq.com
    @date:       2017年4月25日
    @details:    Solution: 149ms 23.71%
'''

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def inOrder(self, n, p, s):
        if n == None: return
        self.inOrder(n.left, p, s)
        if p[0] != None:
            if n.val <= p[0].val:
                if s[0] == None:
                    s[0] = p[0]
                s[1] = n
        p[0] = n
        self.inOrder(n.right, p, s)
        
    def recoverTree(self, n):
        """
        :type n: TreeNode
        :rtype: void Do not return anything, modify n in-place instead.
        """
        p, s = [None], [None, None]
        self.inOrder(n, p, s)
        s[0].val, s[1].val = s[1].val, s[0].val
        


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值