• 530. 平衡二叉树中,相邻节点的最小差 Minimum Absolute Difference in BST


    Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

    Example:

    Input:
    
       1
        
         3
        /
       2
    
    Output:
    1
    
    Explanation:
    The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
    

    Note: There are at least two nodes in this BST.


    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * public int val;
    5. * public TreeNode left;
    6. * public TreeNode right;
    7. * public TreeNode(int x) { val = x; }
    8. * }
    9. */
    10. public class Solution {
    11. public int GetMinimumDifference(TreeNode root) {
    12. if (root == null) {
    13. return 0;
    14. }
    15. int min = Int32.MaxValue;
    16. Stack<TreeNode> stack = new Stack<TreeNode>();
    17. TreeNode current = root;
    18. while (current != null) {
    19. stack.Push(current);
    20. current = current.left;
    21. }
    22. while (stack.Count != 0) {
    23. current = stack.Pop();
    24. if (stack.Count > 0) {
    25. int diff = Math.Abs(stack.Peek().val - current.val);
    26. min = Math.Min(diff,min);
    27. }
    28. TreeNode node = current.right;
    29. while (node != null) {
    30. stack.Push(node);
    31. node = node.left;
    32. if (stack.Count > 0) {
    33. int diff = Math.Abs(stack.Peek().val - current.val);
    34. min = Math.Min(diff,min);
    35. }
    36. }
    37. }
    38. return min;
    39. }
    40. }






  • 相关阅读:
    SOG Tactical Tomahawk F01T 飞虎
    90 压缩干粮 飞虎
    美国陆军国民警卫队不锈钢水瓶 ACU色 飞虎
    CentOS安装RabbitMQ
    如何将EXCEL表中的数据导入数据库中
    Silverlight中的WattingDialog
    WPF ProgressDialog
    DataGrid小扩展
    WPF报表控件
    Misc另外一个世界
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/e62939204dc40c6113eff30dfd622f62.html
Copyright © 2020-2023  润新知