Simple inorder traversal - beats 97% solutions !


  • 0
    A
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution 
    {
        private int x, min;
        public int getMinimumDifference(TreeNode root) 
        {
            if(root == null)
                return 0;
            else
            {
                x = Integer.MAX_VALUE;
                min = Integer.MAX_VALUE;
                
                // perform inorder traversal
                inorder(root);
                
                return min;
            }
        }
        
        private void inorder(TreeNode root)
        {
            if(root == null)
                return;
            else 
            {
                inorder(root.left);
                min = Math.min(min, Math.abs(root.val - x));
                x = root.val;
                inorder(root.right);
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.