O(n) Java solution


  • 0
    Y

    class Solution {
    public int findSecondMinimumValue(TreeNode root) {
    Stack<TreeNode> sta = new Stack<TreeNode>();
    int minVal=-1;
    int secondVal=-1;
    sta.push(root);
    while(!sta.isEmpty())
    {
    TreeNode temp = sta.pop();
    int val=Integer.MAX_VALUE;
    if(temp.left==null && temp.right==null)
    val=temp.val;
    if(temp.left!=null && temp.right!=null)
    {
    val = Math.min(temp.left.val, temp.right.val);
    sta.push(temp.left);
    sta.push(temp.right);
    }
    if(minVal==-1)
    minVal=val;
    else if(minVal>val)
    {
    minVal=val;
    secondVal=minVal;
    }
    else if(minVal==val||secondVal==val)
    continue;
    else
    {
    if(secondVal==-1)
    secondVal=val;
    else
    secondVal=Math.min(val, secondVal);
    }

        }
        return secondVal;     
    }
    

    }


Log in to reply
 

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