Skip to main content

Posts

Showing posts from September, 2017

Binary Tree Paths

Source: LeetCode Solution: We do a preorder traversal add each node in the string followed by an arrow "->" if the current node is a leaf node (have no right or left child) then we add the string to the list, otherwise, we add an arrow and make a recursive call in a preorder fashion. The previous string is stored in stack and we can use it later when the call is returned to add another possible routes from root to the leaf nodes.  Complexity Analysis Time complexity : O ( n ) . n nodes need to be traversed ( n represents the number of nodes in a given tree) .   Solution: public List< String > binaryTreePaths( TreeNode root) { ArrayList< String > path = new ArrayList (); binaryPath(root, "" ,path); return path; } public static void binaryPath( TreeNode root, String s, List< String > path){ if (root == null ) return ;

Merge Two Binary Trees

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. Example 1: Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7    Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7   Note: The merging process must start from the root nodes of both trees.  Source: LeetCode Solution: We traverse both trees in a preorder fashion. In

Invert Binary Search Tree

Invert a binary tree. Example: 4 / \ 2 7 / \ / \ 1 3 6 9   to   4 / \ 7 2 / \ / \ 9 6 3 1  4 / \ 2 7 / \ / \ 1 3 6 9   Trees are crucial data structure in Computer Science. Often trees related problems are solved using recursion as it provides an elegant solution in this particular problem at least. The basic terminology to solve this problem is to swap the left and right values, if you work on the tree from the bottom the to the top swapping the left and right node, the tree will be inverted. Let's go through an example: You can start from left or right. So, starting from the left we have   2 2 (swap the left and right node) / \ => / \ 1 3 3 1   7 7 (similarly, on the right sub-tree) / \ => / \ 6 9 9 6    Which gives,   4 / \ 2 7 / \ / \ 3 1 9 6 And finally, 4 (swap ag