心若向陽,無懼悲傷。 力扣力扣:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
#104 二叉樹的最大深度
給定一個二叉樹,找出其最大深度。
二叉樹的深度爲根節點到最遠葉子節點的最長路徑上的節點數。
說明: 葉子節點是指沒有子節點的節點。
方法一:遞歸
遞歸計算樹的左右子樹的高度。樹的高度=max(左子樹高度,右子樹高度)+1
// java
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right))+1;
}
}
方法二:迭代
BFS層序遍歷+隊列實現
記錄二叉樹的層數,隊列中放入一層的節點,依次拿出,再放入下一層全部節點。
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
int maxheight = 0;
while(queue.size()>0){
maxheight++;
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode node = queue.removeFirst();
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
}
return maxheight;
}
}
DFS前序遍歷+棧實現
// java
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
LinkedList<TreeNode> stack = new LinkedList<>();
stack.push(new Pair<>(root, 1));
int maxheight = 0;
// DFS 每個節點記錄深度
while(!stack.isEmpty()){
Pair<TreeNode, Integer> pair = stack.pop();
TreeNode node = pair.first;
// 更新高度
maxheight = Math.max(maxheight, pair.second);
int curheight = pair.second;
// 子節點入棧,深度加一
if(node.right!=null){
stack.push(new Pair<>(node.right, curheight+1));
}
if(node.left!=null){
stack.push(new Pair<>(node.left, curheight+1));
}
}
return maxheight;
}
}
/* javascript
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
var tmpStack = [
{"key":root,"val":1}
];
var depth = 0;
while(tmpStack.length != 0){
var currObj = tmpStack.pop();
var currNode = currObj.key;
if(currNode != null){
var currNode_depth = currObj.val;
depth = Math.max(depth,currNode_depth);
if(currNode.left != null){
tmpStack.push({"key":currNode.left,"val":currNode_depth + 1});
}
if(currNode.right != null){
tmpStack.push({"key":currNode.right,"val":currNode_depth + 1});
}
}
}
return depth;
};