671. 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 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.
Example 1:
Input:
2
/
2 5
/
5 7
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.

這題我提交了幾次沒過最后用了普通dfs然后記錄最小和次小節點混過去了。
今天看了答案,有兩種比較好的方法:

1

根節點肯定是最小的,那
if node.val == 根節點val,繼續找他的左右孩子
else 返回這個節點的val,因為這個節點的val肯定是這棵樹最小的val。
https://discuss.leetcode.com/topic/102027/c-dfs-recursion

2

用一個set,然后preorder遍歷這棵樹,這個set里的第二個元素就是要找的元素。
https://discuss.leetcode.com/topic/102163/very-simple-java-solution

image.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容