leetcode 98. Validate Binary Search Tree/99. Recover Binary Search Tree

98:

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Example 1:

    2
   / \
  1   3
Binary tree [2,1,3], return true.

Example 2:

    1
   / \
  2   3
Binary tree [1,2,3], return false.

題目意思很明確,就是判斷一個樹是不是一個二分搜索樹,二分搜索樹的一個典型特徵就是對於每一個內部節點,其左邊子樹的所有節點值都要小於這個內部節點的值,這也就是我們判斷的依據。

一個方法,直接中序遍歷,如果合法則必定後一個值大於前一個值,否則返回false。

我使用了另一個大同小異的方法,給每一個節點都設置一個範圍,如果這個節點的值滿足這個範圍則是合法的,否則返回false,那麼這個範圍怎麼設置呢?二分搜素樹的典型特徵,一個節點的左子節點必然小於自己,但不會小於自己的下限,右子節點大於自己,但不會大於自己範圍的上限。例如根節點的範圍設置爲負無窮到正無窮,那麼它的左子節點的範圍就是負無窮到根節點的值,右子節點的範圍就是根節點的值到正無窮,以此類推。

兩種方法的時間複雜度都是O(N)所以應該區別不大。代碼如下:


/**
 * 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:
	long long infinit=21474836499;
	long long minfinit=-2147483699;//因爲樣例的值會達到int的上下限值 
    bool isValidBST(TreeNode* root) {
    	if(root==NULL)
    	return true;
    	if(root->left==NULL&&root->right==NULL)
    	return true;
    	return isValid(root,infinit,minfinit);
    }
    bool isValid(TreeNode* root,long long ma,long long mi)
    {	
    	if(root->val<ma&&root->val>mi)
    	{
    		if(root->left==NULL&&root->right==NULL)
    		return true;
    		if(root->left!=NULL)
    		{
    			if(!isValid(root->left,root->val,mi);)
				return false; 
			}
			if(root->right!=NULL)
			{
				if(!isValid(root->right,ma,root->val);)
				return false;
			}
			return true;
		}
		else
		return false;
	}
};

下面是此題用時最少的一個解法,直接從leetcode上copy下來的:

int key=[](){
    std::ios::sync_with_stdio(false);
    return 0;
}();
class Solution {
public:
    int temp;
    bool temp_exist=false;
    bool isValidBST(TreeNode* root) {
        if(!root)
            return true;
        if(!isValidBST(root->left))
            return false;
        if(!temp_exist){
            temp=root->val;
            temp_exist=true;
        }
        else if(root->val>temp)
            temp=root->val;
        else
            return false;
        if(!isValidBST(root->right))
            return false;
        return true;
    }
};

其實這就是一箇中序遍歷的方法,然後從第一個值開始比較,如果出現小於前一個值的則返回false。

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.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
	long long a=-2147483699,b;
	TreeNode* para_node;//作爲一個參考節點 
	TreeNode* wrong[2];//保存錯位點的地址 
    void recoverTree(TreeNode* root) {
        mid_order(root);
        int temp=wrong[0]->val;
        wrong[0]->val=wrong[1]->val;
        wrong[1]->val=temp;
        return;
    }
    void mid_order(TreeNode* root)
    {
    	if(root!=NULL)
    	{
    		mid_order(root->left);
    		if(a==-2147483699)
    		{
    			a=root->val;
    			para_node=root;
			}
			else
			{
				b=root->val;
				if(b<a)
				{
					if(wrong[0]==NULL)//初始化 
					{
						wrong[0]=para_node;
						wrong[1]=root;
					}
					else
					{
						wrong[1]=root;
						return;	
					}
				}
				a=b;
				para_node=root;
			}
			mid_order(root->right);
		}
	}
};

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