【python】Leetcode每日一题-二叉搜索树节点最小距离
【题目描述】
给你一个二叉搜索树的根节点 root
,返回 树中任意两不同节点值之间的最小差值 。
示例1:
输入:root = [4,2,6,1,3]
输出:1
示例2:
输入:root = [1,0,48,null,null,12,49]
输出:1
提示:
树中节点数目在范围 [2, 100] 内
0 <= Node.val <= 10^5
【分析】
-
dfs中序遍历
-
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
min_ = 100001
pre = 100001
def minDiffInBST(self, root: TreeNode) -> int:
self.dfs(root)
return self.min_
def dfs(self, root):
if root == None:
return
self.dfs(root.left)
if self.pre != 100001:
self.min_ = self.min_ if self.min_ < (root.val - self.pre) else (root.val - self.pre)
self.pre = root.val
self.dfs(root.right)
-
大佬orz,真是涨知识……
-
中序遍历保存数组,再利用搜索树已排序的特性遍历一遍数组即可(只需比较相邻元素
-
设置
pre
指针指向前驱元素,每次比较当前元素与pre
元素即可,不在需要数组 -
使用栈和循环模拟中序优先搜索,其他流程不变,第一次看见用栈实现
dfs
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int minDiffInBST(TreeNode* root) { int minval = INT_MAX; TreeNode* curr = root, *prev = nullptr; stack<TreeNode*> inorder; // 用栈实现递归 while(curr || !inorder.empty()) { if(curr) { inorder.push(curr); curr = curr -> left; //左 } else { curr = inorder.top(); inorder.pop(); if(prev) minval = min(minval, curr -> val - prev -> val); prev = curr; curr = curr -> right; // 右 } } return minval; } };
-