LeetCode.783.二叉搜索树节点最小距离

给定一个二叉搜索树的根节点 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的差值。
 

注意:

二叉树的大小范围在 2 到 100。
二叉树总是有效的,每个节点的值都是整数,且不重复。
本题与 530:https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/ 相同

public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
      public TreeNode getLeft(){
          return this.left;
      }
      public TreeNode getRight(){
          return this.right;
      }
      public int getVal(){
          return this.val;
      }
  }
 
class Solution {
    int[] result=new int[1000];
    int j=0;
    int min=10000;
    public int minDiffInBST(TreeNode root) {
       helper(root);
       for(int i=0;i<j-1;i++){
         if(i<=j-1){
           min=Math.min(min,result[i+1]-result[i]);
         }
       }
       return min;
    }

    public void helper(TreeNode root){
        if(root!=null){
            helper(root.getLeft());
            result[j]=root.getVal();
            j++;
            helper(root.getRight());
        }
    }
}

猜你喜欢

转载自blog.csdn.net/lzc2644481789/article/details/108756090
今日推荐