diff options
author | Jack Sangdahl <[email protected]> | 2025-02-20 22:10:05 -0700 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-02-20 22:10:05 -0700 |
commit | 46d84341f48c823b6b0bd01a3092f364d187b59f (patch) | |
tree | efa4d1889ae60ce2a569f00853e01f50db7a8444 | |
parent | 3a6fd1c4db0b97d79b87161f82e0590a8820d7c1 (diff) | |
download | leetcode-46d84341f48c823b6b0bd01a3092f364d187b59f.tar.gz leetcode-46d84341f48c823b6b0bd01a3092f364d187b59f.zip |
chore: improve python treenode helper to accept full input
-rw-r--r-- | leetcode.py | 25 |
1 files changed, 14 insertions, 11 deletions
diff --git a/leetcode.py b/leetcode.py index 6dcb275..6fdbe28 100644 --- 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 |