设为首页 加入收藏

TOP

LeetCode 99 Recover Binary Search Tree
2015-07-20 17:47:32 来源: 作者: 【 】 浏览:2
Tags:LeetCode 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若若左子树的最大节点的值比根节点大,说明是根节点与左子树的最大节点进行了交换;

3若若右子树的最大节点的值比根节点小,说明是根节点与右子树的最小节点进行了交换;

4若上述三种情况均没有发生,则说明左子树的某两个节点进行了交换或者右子树的某两个节点进行了交换,递归查看左子树和右子树是否有节点进行了交换;

public class Solution {
	private TreeNode findMin(TreeNode root) {
		TreeNode result, l = root, r = root;
		if (root.left != null)
			l = findMin(root.left);
		if (root.right!= null)
			r = findMin(root.right);
		result = l.val < r.val ? l : r;
		return result.val < root.val ? result : root;
	}

	private TreeNode findMax(TreeNode root) {
		TreeNode result, l = root, r = root;
		if (root.left != null)
			l = findMax(root.left);
		if (root.right != null)
			r = findMax(root.right);
		result = l.val > r.val ? l : r;
		return result.val > root.val ? result : root;
	}

	public void recoverTree(TreeNode root) {
		TreeNode l=root,r=root;
		if(root==null||(root.left==null&&root.right==null)) return;
		if(root.left!=null) l=findMax(root.left);
		if(root.right!=null) r=findMin(root.right);
		
		if(l.val>r.val){
			int temp=l.val;
			l.val=r.val;
			r.val=temp;
			return ;
		}else if(l.val>root.val){
			int temp=l.val;
			l.val=root.val;
			root.val=temp;
			return ;
		}else if(r.val
  
   

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HNU Round Robin (约瑟夫) 下一篇Theano学习笔记(四)――导数

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·常用meta整理 | 菜鸟 (2025-12-25 01:21:52)
·SQL HAVING 子句:深 (2025-12-25 01:21:47)
·SQL CREATE INDEX 语 (2025-12-25 01:21:45)
·Shell 传递参数 (2025-12-25 00:50:45)
·Linux echo 命令 - (2025-12-25 00:50:43)