• 783. Minimum Distance Between BST Nodes


    Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.

    Example :

    Input: root = [4,2,6,1,3,null,null]
    Output: 1
    Explanation:
    Note that root is a TreeNode object, not an array.
    
    The given tree [4,2,6,1,3,null,null] is represented by the following diagram:
    
              4
            /   
          2      6
         /     
        1   3  
    
    while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.

    求二叉搜索树任意两节点之间的差值,要求最小

    C++(4ms):
     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int res = INT_MAX ;
    13     int pre = -1 ;
    14     int minDiffInBST(TreeNode* root) {
    15         if (root->left != NULL)
    16             minDiffInBST(root->left) ; 
    17         if (pre >= 0)
    18             res = min(res , root->val - pre) ;
    19         pre = root->val ;
    20         if (root->right != NULL)
    21             minDiffInBST(root->right) ; 
    22         return res ;
    23     }
    24 };
     
  • 相关阅读:
    bfs,队列
    Wannafly挑战赛22 A计数器(裴蜀定理 gcd)
    素数筛模板
    HDU
    HDU
    控制精度-----直接截取,不需四舍五入
    jstl下载与配置
    B. Treasure Hunt
    动态数组vector
    Manacher算法
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8609467.html
Copyright © 2020-2023  润新知