日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

leetcode 543. 二叉树的直径(Java版)

發布時間:2024/2/28 java 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode 543. 二叉树的直径(Java版) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目

https://leetcode-cn.com/problems/diameter-of-binary-tree/

題解 1:暴力法

暴力解法:遍歷這棵樹,當以每個節點為根時,計算 距離,取最大值作為最終結果。

其中,距離 = 左 深度 + 右 深度

其中,深度的計算用 getDepth() 來定義。

/* Definition for a binary tree node. */ 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;} }public class Solution {int max = 0;public int diameterOfBinaryTree(TreeNode root) {inOrder(root);return max;}// 先序遍歷public void inOrder(TreeNode node) {if (node == null) return;int distance = getDepth(node.left, 0) + getDepth(node.right, 0);if (distance > max) max = distance;inOrder(node.left);inOrder(node.right);}// 計算當前節點為根時的樹深度public int getDepth(TreeNode node, int depth) {if (node == null) return depth;else return Math.max(getDepth(node.left, depth + 1), getDepth(node.right, depth + 1));} }

此方法效率很差

題解 2:官方題解

class Solution {int ans;public int diameterOfBinaryTree(TreeNode root) {ans = 1;depth(root);return ans - 1;}public int depth(TreeNode node) {if (node == null) {return 0; // 訪問到空節點了,返回0}int L = depth(node.left); // 左兒子為根的子樹的深度int R = depth(node.right); // 右兒子為根的子樹的深度ans = Math.max(ans, L+R+1); // 計算d_node即L+R+1 并更新ansreturn Math.max(L, R) + 1; // 返回該節點為根的子樹的深度} }作者:LeetCode-Solution 鏈接:https://leetcode-cn.com/problems/diameter-of-binary-tree/solution/er-cha-shu-de-zhi-jing-by-leetcode-solution/

總結

以上是生活随笔為你收集整理的leetcode 543. 二叉树的直径(Java版)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。