【每日一題】【DFS】2022年1月5日-543. 二叉樹的直徑
阿新 • • 發佈:2022-01-05
給定一棵二叉樹,你需要計算它的直徑長度。一棵二叉樹的直徑長度是任意兩個結點路徑長度中的最大值。這條路徑可能穿過也可能不穿過根結點。
答案:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * }*/ class Solution { int max = 0; public int diameterOfBinaryTree(TreeNode root) { dfs(root); return max; } public int dfs(TreeNode root) { if(root.left == null && root.right == null) { return 0; } int leftSize = root.left == null? 0 : dfs(root.left) + 1; int rightSize = root.right == null ? 0 :dfs(root.right) + 1; max = Math.max(max, leftSize + rightSize); return Math.max(leftSize, rightSize); } }
本文來自部落格園,作者:哥們要飛,轉載請註明原文連結:https://www.cnblogs.com/liujinhui/p/15767435.html