[Leetcode] Second Minimum Node in a Binary Tree

Source: Internet
Author: User

[Leetcode] Second Minimum Node in a Binary Tree topic

https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/

Given a non-empty Special binary tree consisting of nodes with the non-negative value, where each node in this tree have ex actly or Zero sub-node. If the node has both sub-nodes, then this node's value is the smaller value among its-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.

Example 1:

Input:
    2
   /\
  2   5
     /\
    5   7

output:5
explanation:the Smallest value is 2, the second Smallest value is 5.

Example 2:

Input:
    2
   /\
  2   2

Output:-1
explanation:the Smallest value is 2, but there isn ' t second small EST value.
Code
34/34 test cases passed.
Runtime:0 ms
/** * Definition for a binary tree node.
 * struct TreeNode {* int val;
 * struct TreeNode *left;
 * struct TreeNode *right;
 * }; */#define INF 0x7fffffff//The minimum value (different from the minimum value of root->val) int traverse (struct treenode* node, struct Treenod) when node nodes are found as subtree
    e* root) {int lval = INF;
    if (node->left! = NULL) {lval = Traverse (node->left, Root);
    } int rval = INF;
    if (node->right! = NULL) {rval = Traverse (node->right, Root);
    } int val = INF;
    if (node->val! = root->val) {val = node->val;
        } if (lval! = root->val) {if (val > lval) {val = lval;
        }} if (Rval! = root->val) {if (val > Rval) {val = rval;
}} return Val;
    } int Findsecondminimumvalue (struct treenode* root) {if (root = = NULL) {return-1;
} if (root->left = = NULL && Root->right = = null) {return-1;    } int val = INF;  val = Traverse (root, root);//val = inf because there is no value different from Root->val if (val = = Root->val | | val = = INF) {return
    -1;
    } else {return val; }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.