File size: 2,682 Bytes
3c88a0f
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "cp-10049", "name": "LeetCode 0543: Diameter Of Binary Tree"}
{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}
{"type": "message", "message": {"role": "user", "content": "Problem: Diameter of Binary Tree (Difficulty: Easy)\nTags: Tree, Depth-First Search, Binary Tree\n\nGiven the root of a binary tree, return the length of the diameter of the tree.\nThe 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 pass through the root.\nThe length of a path between two nodes is represented by the number of edges between them.\n\nExample 1:\nInput: root = [1,2,3,4,5]\nOutput: 3\nExplanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].\n\nExample 2:\nInput: root = [1,2]\nOutput: 1\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 104].\n- -100 <= Node.val <= 100"}}
{"type": "message", "message": {"role": "assistant", "content": "# Time:  O(n)\n# Space: O(h)\n\nclass TreeNode(object):\n    def __init__(self, val=0, left=None, right=None):\n        self.val = val\n        self.left = left\n        self.right = right\n\n\nclass Solution(object):\n    def diameterOfBinaryTree(self, root):\n        \"\"\"\n        :type root: TreeNode\n        :rtype: int\n        \"\"\"\n        def iter_dfs(node):\n            result = 0\n            stk = [(1, [node, [0]])]\n            while stk:\n                step, params = stk.pop()\n                if step == 1:\n                    node, ret = params\n                    if not node:\n                        continue\n                    ret1, ret2 = [0], [0]\n                    stk.append((2, [node, ret1, ret2, ret]))\n                    stk.append((1, [node.right, ret2]))\n                    stk.append((1, [node.left, ret1]))\n                elif step == 2:\n                    node, ret1, ret2, ret = params\n                    result = max(result, ret1[0]+ret2[0])\n                    ret[0] = 1+max(ret1[0], ret2[0])\n            return result\n        \n        return iter_dfs(root)\n\n\n# Time:  O(n)\n# Space: O(h)\nclass Solution2(object):\n    def diameterOfBinaryTree(self, root):\n        \"\"\"\n        :type root: TreeNode\n        :rtype: int\n        \"\"\"\n        def dfs(root):\n            if not root: \n                return 0, 0\n            left_d, left_h = dfs(root.left)\n            right_d, right_h = dfs(root.right)\n            return max(left_d, right_d, left_h+right_h), 1+max(left_h, right_h)\n \n        return dfs(root)[0]\n"}}