tinycodinglm / cp /cp-10049.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
2.68 kB
opencode trace
System You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

User

Problem: Diameter of Binary Tree (Difficulty: Easy)
Tags: Tree, Depth-First Search, Binary Tree

Given the root of a binary tree, return the length of the diameter of the tree.
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 pass through the root.
The length of a path between two nodes is represented by the number of edges between them.

Example 1:
Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].

Example 2:
Input: root = [1,2]
Output: 1

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -100 <= Node.val <= 100
Assistant

Time: O(n)

Space: O(h)

class TreeNode(object):
def init(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def iter_dfs(node):
result = 0
stk = [(1, [node, [0]])]
while stk:
step, params = stk.pop()
if step == 1:
node, ret = params
if not node:
continue
ret1, ret2 = [0], [0]
stk.append((2, [node, ret1, ret2, ret]))
stk.append((1, [node.right, ret2]))
stk.append((1, [node.left, ret1]))
elif step == 2:
node, ret1, ret2, ret = params
result = max(result, ret1[0]+ret2[0])
ret[0] = 1+max(ret1[0], ret2[0])
return result

markdown
return iter_dfs(root)

Time: O(n)

Space: O(h)

class Solution2(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(root):
if not root:
return 0, 0
left_d, left_h = dfs(root.left)
right_d, right_h = dfs(root.right)
return max(left_d, right_d, left_h+right_h), 1+max(left_h, right_h)

markdown
return dfs(root)[0]