algorithm 25

[LeetCode] Construct Binary Tree from Preorder and Inorder Traversal

Problem Solution First element of preorder will always be the root of the tree. Inorder traversal searches left tree and then right tree, so we can find the root element in the list and divide the list up into left and right side(trees). Now we can build those trees. Repeat this process with the root of left tree, which is the second element in the preorder list. Then use the third element as th..

[LeetCode] Lowest Common Ancestor of a Binary Search Tree

Problem Solution Time Complexity O(N) Space Complexity O(1) # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ # If p and q are on the same subtree of the cu..

[LeetCode] Populating Next Right Pointers in Each Node II

Problem Solution The nodes need to know their parent node when they connect to the next node. But since there is no parent value in Node class, the code needs to connect nodes by being on the previous level and updating child nodes. Time Complexity O(N) Space Complexity O(1) """ # Definition for a Node. class Node(object): def __init__(self, val=0, left=None, right=None, next=None): self.val = v..