leetCode 99.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?

思路:因爲有兩個節點錯位, 需要交換回來,最簡單的方法就是中序遍歷,然後排序即可。

代碼如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    ArrayList<TreeNode> list = new ArrayList<TreeNode>();
    public void recoverTree(TreeNode root) {
        preOrder(root);
        TreeNode p = null;
        TreeNode q = null;
        if(list.size() < 2)
            return;
        //冒泡排序
        for(int i = 0; i < list.size() -1; i++){
        	boolean flag = true;
        	for(int j = 0; j < list.size() - 1 - i; j++){
        		if(list.get(j).val > list.get(j+1).val){
        			flag = false;
        			int k = list.get(j).val;
        			list.get(j).val = list.get(j+1).val;
        			list.get(j+1).val = k;
        		}
        	}
        	if(flag){
        		break;
        	}
        }
    }
    /**
     * 中序遍歷
     */ 
    private void preOrder(TreeNode root){
        if(root == null)
            return;
        preOrder(root.left);
        list.add(root);
        preOrder(root.right);
    }
}

但是題目要求儘量O(1)的空間,故換一種方法,還是中序遍歷,不符合要求的節點保存,同時記錄父節點,如果不符合要求的節點只有一個,則說明另一個節點爲父節點。

具體代碼如下“:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
	TreeNode parent = null;
	TreeNode p = null;
    TreeNode q = null;
    public void recoverTree(TreeNode root) {
    	//參考資料:http://blog.csdn.net/worldwindjp/article/details/21694179
        check(root);
        if(p != null && q != null){
        	int k = p.val;
        	p.val = q.val;
        	q.val = k;
        }
    }
    /**
     * 中序遍歷
     */
    private void check(TreeNode root){
    	if(root == null)
    		return;
    	if(root.left != null){
    		check(root.left);
    	}
    	//這段代碼是重點
    	//parent是左子樹父節點
    	if(parent != null && parent.val > root.val){
    		if(p == null){
    			p = parent;
    			q = root;
    		}else{
    			q = root;
    		}
    	}
    	parent = root;
    	if(root.right != null){
    		check(root.right);
    	}
    }
}


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