본문 바로가기

tree7

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. Search in a Binary Search Tree Problem: Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. For example, In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL. Note that an empty t.. 2020. 6. 16.
LeetCode. Convert Sorted Array to Binary Search Tree [Trees] Problem: Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example: -Summary- Solve by recursive function call 1. First, find a root first by finding the midpoint of the given integer array. 2.. 2020. 6. 7.
LeetCode. Binary Tree Level Order Traversal [Trees] Problem: Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], -Summary- Solve by BFS (Breadth-First Search) Algorithm using queue 1. Create a queue and keep adding the value if left or right subtree exists 2. While adding the value to the queue, we pop and add the value to the.. 2020. 6. 7.
LeetCode. Symmetric Tree [Trees] Problem: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: But the following [1,2,2,null,3,null,3] is not: -Summary- 1. If a tree has no root or root itself exist, it will always return True 2. Otherwise, we keep check below condition recursively of the Tree's left and right subtree - leftSub.. 2020. 6. 7.
LeetCode. Validate Binary Search Tree [Trees] Problem: Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. -Summary- 1. Create a helper function to r.. 2020. 6. 6.