Leetcode
  • Leetcode Questions
  • Runtime Screenshots
  • DataStructure
    • Leetcode 394. Decode String
    • Leetcode 225. Implement Stack Using Queues
    • Leetcode 336. Palindrome Pairs
    • Leetcode 316. Remove Duplicate Letters
    • Leetcode 206. Reverse Linked List
    • Leetcode 347. Top K Frequent Elements
    • Leetcode 227. Basic Calculator II
    • Leetcode 224. Basic Calculator
  • Linear
    • Leetcode 23. Merge k Sorted Lists
    • Leetcode 48. Rotate Image
    • Leetcode 6. ZigZag Conversion
    • Leetcode 438. Find All Anagrams in a String
    • Leetcode 189. Rotate Array
    • LeetCode 56. Merge Intervals
    • Leetcode 4. Median of Two Sorted Array
    • Leetcode 3. Longest Substring Without Repeating Characters
    • Leetcode 8. String to Integer (atoi)
    • Leetcode 5. Longest Palindromic Substring
    • Leetcode 11. Container With Most Water
  • Tree
    • Leetcode 103. Binary Tree Zigzag Level Order Traversal
    • Leetcode 508. Most Frequent Subtree Sum
    • Leetcode 226. Invert Binary Tree
    • Leetcode 222. Count Complete Tree Nodes
    • Leetcode 250. Count Univalue Subtrees
    • Leetcode 285. Inorder Successor in BST
    • Leetcode 230. Kth Smallest Element in a BST
    • Leetcode 543. Diameter of Binary Tree
    • Leetcode 199. Binary Tree Right Side View
  • Math
    • Leetcode 50. Power(x, n)
    • Leetcode 166. Fraction to Recurring Decimal
    • Leetcode 7. Reverse Integer
    • Leetcode 360. Sort Transformed Array
    • Leetcode 367. Valid Perfect Square
    • Leetcode 12. Integer to Roman
  • DynamicProgramming
    • Leetcode 10. Regular Expression Matching
    • Leetcode 253. Meeting Rooms II
    • Leetcode 303. Range Sum Query
    • Leetcode 22. Generate Parentheses
  • Graph
    • Leetcode 142. Linked List Cycle II
    • Leetcode 261. Graph Valid Tree
    • Leetcode 339. Nested List Weight Sum
    • Leetcode 207. Course Schedule
  • OODesign
    • Leetcode 295. Find Media From Data Stream
Powered by GitBook
On this page
  • 题目
  • 思路
  • 解答
  • Complexity Analysis
  • 拓展
  • 总结
  • Reference

Was this helpful?

  1. Tree

Leetcode 543. Diameter of Binary Tree

题目

Given a binary tree, you need to compute the length of the tree's diameter. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not path through the root.s

Example:

          1
         / \
        2   3
       / \     
      4   5

return 3, which is the length of the path [4,2,13] or [5,2,1,3]

Note: The length of the path between two node is represented by the number of edges between them.

思路

对于这类题型,个人倾向于将它拆分为三个部分来看待。对于root来讲,最长的路径可能存在于:

  • 左边的子树, left sub tree

  • 右边的子树,right sub tree

  • 或者经过root,贯穿左右

这样的模式很容易启发我们使用递归。前两个情况可以被递归解决,但是第三种情况如何处理呢?已知最长路径 贯穿root,那么我们知道左边的路径一定是从root到最远的leaf,右边同理,否则这路径一定不是最长的。 因此,我们发现第三种情况为左右子树高度相加再加1。

值得注意的是,因为我们想求最长路径,我们需要将三种情况进行比较,并在递归的过程中,保存一个全局的 变量来记录最长。

解答

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    private static int longestPath = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        maxDepth(root);
        return longestPath;
    }

    private int maxDepth(TreeNode node) {
        if (node == null) return 0;
        int left = maxDepth(node.left);
        int right = maxDepth(node.right);

        // Compare case 3 with global max
        longestPath = Math.max(longestPath, left + right);

        return Math.max(left, right) + 1;
    }
}

Complexity Analysis

  • Time Complexity: O(n). 我们遍历了树上的所有节点。

  • Space Complexity: O(n). 我们递归的stack space需要储存所有的节点。

拓展

  • 运用循环的方式能解决这道题吗?循环能够减少空间的使用吗?

  • 用BFS能解决这道题吗?

  • O(n)的时间复杂度是最优解吗?

总结

这道题是经典的DFS的应用题。一如既往,我们依然尝试将问题拆分成几种不同的情况,并观察其中大部分情况是否 是递归的解答。然后,对于剩下的某种、某几种无法递归得出答案的解答,我们则去思考如何利用现有条件求解。 最终,我们把所有的情况整合在一起,得出整个题目的答案。

Reference

PreviousLeetcode 230. Kth Smallest Element in a BSTNextLeetcode 199. Binary Tree Right Side View

Last updated 5 years ago

Was this helpful?

Leetcode Official Solution