Wednesday, October 30, 2019

530. Minimum Absolute Difference in BST

Here is the link.

C# Inorder traversal solution

Oct. 30, 2019
To traverse the binary search tree in ascending order, inorder traversal is chosen. Inorder traversal is to visit left node, root node and then right node. The previous node is declared as static variable, to work with more than one test cases, it is important to reset previous node to null.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _530_minimum_difference_in_BST
{
    class Program
    {
        public class TreeNode {
            public int val;
            public TreeNode left;
            public TreeNode right;
            public TreeNode(int x) { val = x; }
        }

        static void Main(string[] args)
        {
            var node1 = new TreeNode(1);
            var node5 = new TreeNode(5);
            var node3 = new TreeNode(3);

            node1.right = node5;
            node5.left = node3;

            var result = GetMinimumDifference(node1); 
        }

        static TreeNode previous;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        public static int GetMinimumDifference(TreeNode root)
        {
            previous = null;  // caught by online judge - Oct. 30, 2019
            int minDiff = Int32.MaxValue;
            traverseInorder(root, ref minDiff);
            return minDiff;
        }

        /// Left, Root, right
        private static void traverseInorder(TreeNode root, ref int minDiff)
        {
            if (root == null)
                return;
            traverseInorder(root.left, ref minDiff);

            // handle root node
            if (previous != null)
            {
                var current = root.val - previous.val;
                minDiff = current < minDiff ? current : minDiff;
            }

            previous = root;

            traverseInorder(root.right, ref minDiff);
        }
    }
}


No comments:

Post a Comment