C# DFS solution


  • 0
    B
    public class Solution 
    {
        public int FindSecondMinimumValue(TreeNode root) 
        {
            if (root == null) return -1;
    
            var result = DFS(root);
            
            if (result == int.MaxValue) return -1;
            
            return result;
        }
    
        private int DFS(TreeNode root)
        {
            if (root == null) return int.MaxValue;
    
            if (root.left != null)
            {
                if (root.left.val == root.right.val)
                {
                    return Math.Min(DFS(root.left), DFS(root.right));
                }
                else
                {
                    if (root.left.val == root.val)
                    {
                        return Math.Min(root.right.val, DFS(root.left));
                    }
                    else
                    {
                        return Math.Min(root.left.val, DFS(root.right));
                    }
                }
            }
    
            return int.MaxValue;
        }
    }
    

  • 0
    C
    public class Solution {
        public int FindSecondMinimumValue(TreeNode root)
        {
            if (root == null || root.left == null || root.right == null) return -1;
    
            var l = root.left.val;
            if (root.val == l) l = FindSecondMinimumValue(root.left);
            
            var r = root.right.val;
            if (root.val == r) r = FindSecondMinimumValue(root.right);
            
            if (l == -1) return r;
            else if (r == -1) return l;
            return Math.Min(l, r);
        }
    }
    

Log in to reply
 

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