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);
        }
    };
  • 相关阅读:
    chrome更新后,恢复本地丢失的书签和历史记录
    redis 集合set 使用 rediscluster 使用交集
    git 删除分支恢复
    SQL语句性能优化
    A调用B,b有事务,a没有
    Unable to tunnel through proxy. Proxy returns "HTTP/1.0 407 Proxy Authentica 问题处理
    fasnjson 转换
    String.format()的详细用法
    传递json
    基础入门-加密编码算法
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433960.html
Copyright © 2011-2022 走看看