第 18 日:二叉樹的深度
題目鏈接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/
題目

解題
-
前序遍歷+記錄
解題思路:
這題很簡單,要求二叉樹的深度,那就設變數max存盤遍歷實時的深度,最后遍歷完肯定就是最大深度了
詳細代碼如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max=0;
public int maxDepth(TreeNode root) {
dfs(root,1);
return max;
}
public void dfs(TreeNode node,int depth){
if(node==null) return;
//記錄最大值
if(depth>max) max=depth;
dfs(node.left,depth+1);
dfs(node.right,depth+1);
}
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/345667.html
標籤:其他
