[英]Why won't my solution work to find minimum depth of a binary tree?
我不明白我找到二叉樹最小深度的解決方案是如何工作的? 我究竟做錯了什么?
如果您感到好奇,可以使用以下鏈接來解決問題: https : //leetcode.com/problems/minimum-depth-of-binary-tree/submissions/
public int minDepth(TreeNode root) {
if(root == null) return 0;
int left = minDepth(root.left);
int right = minDepth(root.right);
int ans = Math.min(left, right) + 1;
return ans;
}
如果只有一方為null ,那么你的代碼將不起作用
3
/ \
20
/ \
15 7
因為它將返回1(而3
不是葉子)。
你需要測試一方是否為空 ,忽略它並處理另一方
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.