leetcode 543. 二叉树的直径(Java版)
生活随笔
收集整理的這篇文章主要介紹了
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版)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oh-my-zsh 国内网络快速安装方法
- 下一篇: leetcode 551. 学生出勤记录