Leetcode783.Minimum Distance Between BST Nodes二叉搜索树结点最小距离

给定一个二叉搜索树的根结点 root, 返回树中任意两节点的差的最小值。

示例:

输入: root = [4,2,6,1,3,null,null] 输出: 1 解释: 注意,root是树结点对象(TreeNode object),而不是数组。 给定的树 [4,2,6,1,3,null,null] 可表示为下图: 4 / 2 6 / 1 3 最小的差值是 1, 它是节点1和节点2的差值, 也是节点3和节点2的差值。

注意:

  1. 二叉树的大小范围在 2 到 100。
  2. 二叉树总是有效的,每个节点的值都是整数,且不重复。

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};

class Solution {
public:
    int minDiffInBST(TreeNode* root)
    {
        if(root ->left != NULL && root ->right != NULL)
        {
            int res = min(abs(root ->val - SLeft(root ->left)), abs(root ->val - SRight(root ->right)));
            return min(res, min(minDiffInBST(root ->right), minDiffInBST(root ->left)));
        }
        else if(root ->left == NULL && root ->right == NULL)
        {
            return INT_MAX;
        }
        else if(root ->left == NULL)
        {
            int res = abs(root ->val - SRight(root ->right));
            return min(res, minDiffInBST(root ->right));
        }
        else
        {
            int res = abs(root ->val - SLeft(root ->left));
            return min(res, minDiffInBST(root ->left));
        }
    }

    int SLeft(TreeNode* root)
    {
        if(root ->right == NULL)
            return root ->val;
        return SLeft(root ->right);
    }

    int SRight(TreeNode* root)
    {
        if(root ->left == NULL)
            return root ->val;
        return SRight(root ->left);
    }
};
原文地址:https://www.cnblogs.com/lMonster81/p/10433961.html