본문 바로가기

Recursion4

LeetCode. Sum Root to Leaf Numbers Problem: Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. Note: A leaf is a node with no children. -Summary- Used recursive DFS. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=Non.. 2020. 6. 27.
LeetCode. Count Complete Tree Nodes Problem: Given a complete binary tree, count the number of nodes. Note: Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Example: -Summary- Solve by recursion 1. if the root exists.. 2020. 6. 24.
LeetCode 226. Invert Binary Tree Problem: Invert a binary tree. Example: -Summary- Solved recursively 1. Until root node exist, we keep traverse left and right and change the left and right subtree by exchanging value. (By calling the function recursively) Here is another solution by solving this iteratively using stack. def invertTree(self, root): stack = [root] while stack: node = stack.pop() if node: node.left, node.right = .. 2020. 6. 20.
Floor and Ceiling of a Binary Search Tree Problem: Given an integer k and a binary search tree, find the floor (less than or equal to) of k, and the ceiling (larger than or equal to) of k. If either does not exist, then print them as None. Here is the definition of a node for the tree. -Summary- 1. if root node is empty we return none value for both floor and ceil. 2. if root node is equal with k, return floor and cell with k value 3. i.. 2020. 6. 19.