Skip to content

Commit 8af9825

Browse files
committed
added construct string from tree
1 parent c376f77 commit 8af9825

3 files changed

Lines changed: 43 additions & 2 deletions

File tree

leetcode/src/binary_trees/lc_543_diameter_of_a_tree/tree_diameter.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,23 @@ class TreeNode:
22
def __init__(self, val=0, left=None, right=None):
33
self.val = val
44
self.left = left
5-
self.right = right
5+
self.right = right
6+
7+
8+
def tree_diameter(root):
9+
def tree_diameter_helper(node):
10+
nonlocal diameter
11+
if node is None:
12+
return 0
13+
14+
left = tree_diameter_helper(node.left)
15+
right = tree_diameter_helper(node.right)
16+
17+
diameter = max(diameter, left + right)
18+
19+
return max(left, right) + 1
20+
21+
diameter = 0
22+
tree_diameter_helper(root)
23+
24+
return diameter

leetcode/src/binary_trees/lc_572_subtree_of_another_tree/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.
44

5-
A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.
5+
A subtree of a binary tree is a tree that consists of a node in tree and all of this node's descendants. The tree could also be considered as a subtree of itself.
66
### Example 1
77

88
![Subtree of Another Tree Example 1](https://assets.leetcode.com/uploads/2021/04/28/subtree1-tree.jpg)
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class TreeNode:
2+
def __init__(self, val=0, left=None, right=None):
3+
self.val = val
4+
self.left = left
5+
self.right = right
6+
7+
def treeStr(root):
8+
def treeStrHelper(node):
9+
result = str(node.val)
10+
11+
if node.left:
12+
result += "(" + treeStrHelper(node.left) + ")"
13+
14+
if node.right:
15+
if not node.left:
16+
result += "()"
17+
18+
result += "(" + treeStrHelper(node.right) + ")"
19+
20+
return result
21+
22+
return treeStrHelper(root)

0 commit comments

Comments
 (0)