zoukankan      html  css  js  c++  java
  • 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);
        }
    };
  • 相关阅读:
    python装饰器的4种类型:函数装饰函数、函数装饰类、类装饰函数、类装饰类
    python中将函数赋值给变量时需要注意的一些问题
    python获得命令行输入的参数
    Python实现语音识别和语音合成
    pymysql
    Matplotlib
    级联,映射
    处理丢失数据
    Numpy,Pandas,Matplotlib
    crawlSpider,分布式爬虫,增量式爬虫
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433961.html
Copyright © 2011-2022 走看看