783. Minimum Distance Between BST Nodes - Easy 前往題目 想法 左右子樹和父節點比較就好 思路這樣的想法問題是孫子可能跟爺爺更近,相較於兒子 inorder可以在BST從最小數節點迭代到最大數節點 Code class Solution { int min; TreeNode prev; public int minDiffInBST(TreeNode root) { min = Integer.MAX_VALUE; prev = null; inorder(root); return min; } private void inorder(TreeNode cur) { if (cur == null) return; inorder(cur.left); // Not in the root node if (prev != null) { min = Math.min(min, Math.abs(cur.val - prev.val)); } prev = cur; inorder(cur.right); } } Leetcode > Easy #Leetcode #心得 #Binary Search Tree #Binary Tree #Depth-First Search #Breadth-First Search #Tree 783. Minimum Distance Between BST Nodes - Easy https://f88083.github.io/2024/10/26/783-Minimum-Distance-Between-BST-Nodes-Easy/ 作者 Simon Lai 發布於 2024年10月26日 許可協議 1443. Minimum Time to Collect All Apples in a Tree - Medium 上一篇 450. Delete Node in a BST - Medium 下一篇 Please enable JavaScript to view the comments