# 0543. Diameter of Binary Tree ###### tags: `Leetcode` `Easy` `FaceBook` `DFS` Link: https://leetcode.com/problems/diameter-of-binary-tree/ ## 思路 DFS 过程中记录最大值 一定要注意它找的不是经过几个node,要把经过的node个数-1 ## Code ```java= class Solution { int maxLen = 0; public int diameterOfBinaryTree(TreeNode root) { dfs(root); return maxLen; } public int dfs(TreeNode root){ if(root == null) return 0; int leftLen = dfs(root.left); int rightLen = dfs(root.right); maxLen = Math.max(leftLen+rightLen, maxLen); return Math.max(leftLen, rightLen)+1; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up