給定乙個二叉樹,找出其最大深度。
二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。
說明: 葉子節點是指沒有子節點的節點。
示例:給定二叉樹 [3,9,20,null,null,15,7],
3
/
9 20
/ 15 7
返回它的最大深度 3 。
題目分析:還是使用遞迴,找出左右兩邊的層數,最後加一(根節點)
錯點分析:
/**
* definition for a binary tree node.
* public class treenode
* }*/class
solution
int left =
judgedepth
(root.left)
;int right =
judgedepth
(root.right);if
(left>right)
else
}public
intjudgedepth
(treenode tree)
else
}else
}}
不應該是有左孩子就一直往左邊找,而是應該左右一起找,返回左右兩邊中最大的數
修改**:
/**
* definition for a binary tree node.
* public class treenode
* }*/class
solution
int left =
judgedepth
(root.left)
;int right =
judgedepth
(root.right);if
(left>right)
else
}public
intjudgedepth
(treenode tree)
else
}}
提交成功,還需要精簡一下**,上面那個if和else顯得比較冗餘
/**
* definition for a binary tree node.
* public class treenode
* }*/class
solution
int left =
judgedepth
(root.left)
;int right =
judgedepth
(root.right)
;return left>right ? left+
1: right+1;
}public
intjudgedepth
(treenode tree)
else
}}
寒假LeetCode打卡(4)
給定乙個二叉樹,檢查它是否是映象對稱的。例如,二叉樹 1,2,2,3,4,4,3 是對稱的。1 2 2 3 4 4 3 但是下面這個 1,2,2,null,3,null,3 則不是映象對稱的 1 2 2 3 3分析題目 要判斷映象二叉樹,即左樹的左孩子等於右樹的右孩子,左樹的右孩子等於右樹的左孩子,...
寒假LeetCode打卡(9)
給定乙個鍊錶,判斷鍊錶中是否有環。為了表示給定鍊錶中的環,我們使用整數 pos 來表示鍊錶尾連線到鍊錶中的位置 索引從 0 開始 如果 pos 是 1,則在該鍊錶中沒有環。示例 1 輸入 head 3,2,0,4 pos 1 輸出 true 解釋 鍊錶中有乙個環,其尾部連線到第二個節點。示例 2 輸...
2021寒假打卡
本週計畫主要學習dp,但還是有所變動過,先學習了一下貪心思想。貪心法就是遵循某種規則,不斷貪心地選取當前最優策略的演算法設計方法。搜尋演算法和動態規劃演算法是在多種策略中選取最優解。而貪心演算法則是一直遵循某種規則,不斷地選取當前最優策略。另,記錄今天思路錯誤的一道題 給定乙個整形陣列arr,已知其...