<style> html, body, .ui-content { background: #222222; color: #00BFFF; } ::-webkit-scrollbar { width: 10px; } ::-webkit-scrollbar-track { background: transparent; } ::-webkit-scrollbar-thumb { background: linear-gradient(180deg, #2BE8CF60 0%, #2B83E860 100%); border-radius: 3px; } ::-webkit-scrollbar-thumb:hover { background: linear-gradient(180deg, #2BE8CF95 0%, #2B83E895 100%); } /* 設定 code 模板 */ .markdown-body code, .markdown-body tt { background-color: #ffffff36; } .markdown-body .highlight pre, .markdown-body pre { color: #ddd; background-color: #00000036; } .hljs-tag { color: #ddd; } .token.operator { background-color: transparent; } </style> ###### tags: `Leetcode` # 783. Minimum Distance Between BST Nodes ###### Link : https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/ ## 題目 找任兩個node最小的差 ## 程式碼 (with inorder list) ```cpp= /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int minDiffInBST(TreeNode* root) { inorder.clear(); inorderRec(root);//inorder recursion(inorder可由小到大) int ans = inorder[1] - inorder[0]; for(int i = 2;i < inorder.size();++i){//找最小差異 if(inorder[i] - inorder[i - 1] < ans) ans = inorder[i] - inorder[i - 1]; } return ans; } void inorderRec(TreeNode *node){//inorder遞迴 if(!node) return; inorderRec(node->left); inorder.push_back(node->val); inorderRec(node->right); return; } private: vector<int> inorder; }; ``` ## 程式碼 (without inorder list) ```cpp= /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int minDiffInBST(TreeNode* root) { diff = INT_MAX; prev = NULL; inorderRec(root); return diff; } private: void inorderRec(TreeNode *node){ if(!node) return; inorderRec(node->left); if(prev)//prev != NULL diff = min(diff, node->val - prev->val);//更新最小值 prev = node;//記錄好前一個 inorderRec(node->right); return; } TreeNode *prev;//存前一個 int diff; }; ```