1. 程式人生 > >[Leetcode] 二叉樹的最小差

[Leetcode] 二叉樹的最小差

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
const int inf=0x3f3f3f;
class Solution {
public:
    int getLR(TreeNode *root){
        if(root == NULL) return inf;
        TreeNode *p1,*p2;
        int val1=inf;
        int val2=inf;
        int val3=inf;
        int val4=inf;
        if(root->left){
            p1=root->left;
            while(p1->right){
                p1=p1->right;
            }    
            val1=abs(root->val-p1->val);
            val3=TreeNode(root->left);
            val1=val1<val3?val1:val3;
        }
        if(root->right){
            p2=root->right;
            while(p1->left){
                p2=p2->right;
            }
            val2=abs(root->val-p2->val);
            val4=TreeNode(root->right);
            val2=val2<val4?val2:val4;
        }
        return val1<val2?val1:val2;
    
    }
    int getMinimumDifference(TreeNode* root) {
        int left;
        int right;
        if(root->left == NULL && root->right == NULL) return inf;
        
        return getLR(root);
        
    }

};