0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Leetcode 530. Minimum Absolute Difference in BST

Posted at

アプローチ

DFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {

    public int result = Integer.MAX_VALUE;
    public ArrayList<Integer> list;
    public int getMinimumDifference(TreeNode root) {
        list = new ArrayList<>();
        dfs(root);
        return result;
    }

    public void dfs(TreeNode node) {
        list.add(node.val);
        if (node.left != null) {
            for(int i = 0; i < list.size(); i++){
               result= Math.min(  Math.abs(list.get(i) - node.left.val) , result);
            }
            
            dfs(node.left);
        }
        if (node.right != null) {
            for(int i = 0; i < list.size(); i++){
                result= Math.min(  Math.abs(list.get(i) - node.right.val) , result);
            }
            dfs(node.right);
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?