commit 46d84341f48c823b6b0bd01a3092f364d187b59f
parent 3a6fd1c4db0b97d79b87161f82e0590a8820d7c1
Author: Jack Sangdahl <jack@pngu.org>
Date: Thu, 20 Feb 2025 22:10:05 -0700
chore: improve python treenode helper to accept full input
Diffstat:
1 file changed, 14 insertions(+), 11 deletions(-)
diff --git a/leetcode.py b/leetcode.py
@@ -1,23 +1,26 @@
-class TreeNode(object):
+from collections import deque
+
+
+class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
-def list_to_tree(input):
- if not input:
+def treenode_build(vals):
+ if not vals or vals[0] is None:
return None
- root = TreeNode(input[0])
- q, i = [root], 1
- while i < len(input):
- curr = q.pop(0)
- if input[i] is not None:
- curr.left = TreeNode(input[i])
+ root = TreeNode(vals[0])
+ q, i = deque([root]), 1
+ while q and i < len(vals):
+ curr = q.popleft()
+ if vals[i] is not None:
+ curr.left = TreeNode(vals[i])
q.append(curr.left)
i += 1
- if i < len(input) and input[i] is not None:
- curr.right = TreeNode(input[i])
+ if i < len(vals) and vals[i] is not None:
+ curr.right = TreeNode(vals[i])
q.append(curr.right)
i += 1
return root