码迷,mamicode.com
首页 > 其他好文 > 详细

783. Minimum Distance Between BST Nodes

时间:2018-11-27 10:10:15      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:tween   imu   code   col   max   treenode   between   null   res   

/**
 * 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:
    int minDiffInBST(TreeNode* root) {
        if (root == NULL)
            return 0;
        int res = INT_MAX;
        helper(root, res, NULL);
        return res;
    }
    TreeNode* helper(TreeNode* root, int &res, TreeNode* prev) {
        if (root->left) {
            TreeNode* left = helper(root->left, res, prev);
            res = min(res, root->val - left->val);
            prev = left;
        }
        
        if (prev)
            res = min(res, root->val - prev->val);
        
        if (root->right)
            return helper(root->right, res, root);
        else
            return root;
    }
};

 

783. Minimum Distance Between BST Nodes

标签:tween   imu   code   col   max   treenode   between   null   res   

原文地址:https://www.cnblogs.com/JTechRoad/p/10024191.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!