671. Second Minimum Node In a Binary Tree

来源:互联网 发布:辐射4捏脸载入json 编辑:程序博客网 时间:2024/05/29 19:25

Given a non-empty special binary tree consisting of nodes with the
non-negative value, where each node in this tree has exactly two or
zero sub-node. If the node has two sub-nodes, then this node’s value
is the smaller value among its two sub-nodes.

Given such a binary tree, you need to output the second minimum value
in the set made of all the nodes’ value in the whole tree.

If no such second minimum value exists, output -1 instead.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public int findSecondMinimumValue(TreeNode root) {        int small = -2;        int secondSmall = -1;        Queue<TreeNode> que = new LinkedList<TreeNode>();        if(root == null){            return -1;        }        que.add(root);        while(que.peek() != null){            int level = que.size();            for( int i = 0;i<level;++i){                TreeNode node = que.poll();                if(node.left!=null){                    que.offer(node.left);                }                if(node.right!=null){                    que.offer(node.right);                }                if(small == -2){                    small = node.val;                    continue;                }                if(secondSmall == -1 && node.val > small){                    secondSmall = node.val;                    continue;                }                if(node.val<small){                    secondSmall = small;                    small = node.val;                    continue;                }                if(node.val < secondSmall){                    small = node.val;                    continue;                }            }        }        return secondSmall;    }}
原创粉丝点击