Binary tree in Python
A binary tree is a tree data structure in which each node has at most two children, referred to as the left child and the right child.
[Leetcode 105] Construct Binary Tree from Preorder and Inorder Traversal
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
Example 1:
1 | Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] |
Example 2:
1 | Input: preorder = [-1], inorder = [-1] |
Constraints:
- 1 <= preorder.length <= 3000
- inorder.length == preorder.length
- -3000 <= preorder[i], inorder[i] <= 3000
- preorder and inorder consist of unique values.
- Each value of inorder also appears in preorder.
- preorder is guaranteed to be the preorder traversal of the tree.
- inorder is guaranteed to be the inorder traversal of the tree.
Solution:
1 | # Definition for a binary tree node. |
[Leetcode 106] Construct Binary Tree from Inorder and Postorder Traversal
Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.
Example 1:
1 | Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] |
Example 2:
1 | Input: inorder = [-1], postorder = [-1] |
Constraints:
- 1 <= inorder.length <= 3000
- postorder.length == inorder.length
- -3000 <= inorder[i], postorder[i] <= 3000
- inorder and postorder consist of unique values.
- Each value of postorder also appears in inorder.
- inorder is guaranteed to be the inorder traversal of the tree.
- postorder is guaranteed to be the postorder traversal of the tree.
Solution:
1 | # Definition for a binary tree node. |
[Leetcode 129] Sum Root to Leaf Numbers
You are given the root of a binary tree containing digits from 0 to 9 only.
Each root-to-leaf path in the tree represents a number.
For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
A leaf node is a node with no children.
Example 1:
1 | 1 |
Constraints:
- The number of nodes in the tree is in the range [1, 1000].
- 0 <= Node.val <= 9
- The depth of the tree will not exceed 10.
Solution:
1 | # Definition for a binary tree node. |
[Leetcode 226] Invert Binary Tree
Given the root of a binary tree, invert the tree, and return its root.
Example 1:
1 | Input: root = [4,2,7,1,3,6,9] |
Example 2:
1 | Input: root = [2,1,3] |
Example 3:
1 | Input: root = [] |
Constraints:
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
1 | # Definition for a binary tree node. |