Binary Search Tree
Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get prefix expression on of an expression tree.
Why we use Preorder traversal?
// iterative public boolean isSymmetric(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); queue.add(root); while(!queue.isEmpty()) { TreeNode t1 = queue.poll(); TreeNode t2 = queue.poll(); if(t1 == null && t2 == null) continue; if(t1 == null || t2 == null) return false; if(t1.val != t2.val) return false; queue.add(t1.left); queue.add(t2.right); queue.add(t1.right); queue.add(t2.left); } return true; } // recursive version public boolean isSymmetric(TreeNode root) { return isMirror(root, root); } private boolean isMirror(TreeNode t1, TreeNode t2) { if(t1 == null && t2 == null) return true; if(t1 == null || t2 == null) return false; return t1.val == t2.val && isMirror(t1.left, t2.right) && isMirror(t1.right, t2.left); }
101. Symmetric Tree 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: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3 Note: Bonus points if you could solve it both recursively and iteratively.
public TreeNode sortedArrayToBST(int[] num) { if (num.length == 0) return null; return sortedArrayToBST(num, 0, num.length - 1); } public TreeNode sortedArrayToBST(int[] num, int start, int end) { if (start > end) return null; int mid = (start + end) / 2; TreeNode root = new TreeNode(num[mid]); root.left = sortedArrayToBST(num, start, mid - 1); root.right = sortedArrayToBST(num, mid + 1, end); return root; }
108. Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
public boolean isBalanced(TreeNode root) { if(root == null) return true; if(root.left == null && root.right == null) return true; int leftHeight = getHeight(root.left); int rightHeight = getHeight(root.right); return Math.abs(leftHeight - rightHeight) < 2 && isBalanced(root.left) && isBalanced(root.right); } private int getHeight(TreeNode root) { // An empty tree has height -1 if(root == null) return -1; return 1 + Math.max(getHeight(root.left), getHeight(root.right)); }
110. Balanced Binary Tree Given a binary tree, determine if it is height-balanced. 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 1: Given the following tree [3,9,20,null,null,15,7]: 3 / \ 9 20 / \ 15 7 Return true. Example 2: Given the following tree [1,2,2,3,3,null,null,4,4]: 1 / \ 2 2 / \ 3 3 / \ 4 4 Return false.
public int minDepth(TreeNode root) { if(root == null) return 0; Queue<TreeNode> queue = new LinkedList<>(); Queue<Integer> counts = new LinkedList<>(); queue.add(root); counts.add(1); while(!queue.isEmpty()) { TreeNode curr = queue.poll(); int count = counts.poll(); if(curr.left == null && curr.right == null) { return count; } if(curr.left != null) { queue.add(curr.left); counts.add(count + 1); } if(curr.right != null) { queue.add(curr.right); counts.add(count + 1); } } return 0; }
111. Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its minimum depth = 2.
public boolean hasPathSum(TreeNode root, int sum) { if(root == null) return false; if(root.val == sum && (root.left == null && root.right == null)) { return true; } return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); }
112. Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> result = new ArrayList<>(); List<Integer> currList = new ArrayList<>(); if(root == null) return result; pathSum(root, sum, result, currList); return result; } private void pathSum(TreeNode root, int sum, List<List<Integer>> result, List<Integer> currList) { if(root == null) { return; } if(root.left == null && root.right == null) { if(root.val == sum) { currList.add(root.val); result.add(new ArrayList<>(currList)); currList.remove(currList.size() - 1); } } currList.add(root.val); pathSum(root.left, sum - root.val, result, currList); pathSum(root.right, sum - root.val, result, currList); currList.remove(currList.size() - 1); }
113. Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 Return: [ [5,4,11,2], [5,8,4,5] ]
public void flatten(TreeNode root) { if (root == null) return; Queue<TreeNode> queue = new LinkedList<TreeNode>(); populatePreorder(queue, root); TreeNode curr = queue.poll(); while(!queue.isEmpty()) { curr.right = queue.poll(); curr.left = null; curr = curr.right; } } private void populatePreorder(Queue<TreeNode> q, TreeNode node) { if (node == null) return; q.add(node); populatePreorder(q, node.left); populatePreorder(q, node.right); } Follow up - O(1) space solution: private TreeNode prev; public void flatten(TreeNode root) { if (root == null) return; flatten(root.right); flatten(root.left); root.right = prev; root.left = null; prev = root; }
114. Given a binary tree, flatten it to a linked list in-place. For example, given the following tree: 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6
In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder itraversal s reversed, can be used.
Why we use Inorder traversal?
r.left != null) { queue.add(curr.left); } if(curr.right != null) { queue.add(curr.right); } } } return root; }
117. Populating Next Right Pointers in Each Node II Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. Note: You may only use constant extra space. Recursive approach is fine, implicit stack space does not count as extra space for this problem. You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). Example: Given the following perfect binary tree, 1 / \ 2 3 / \ / \ 4 5 6 7 After calling your function, the tree should look like: 1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
Idea is to do a level order traversal and in each step pass along the ((parent x 10) + child ) as the current value. If it ends up being a leaf node add it to the sum. public int sumNumbers(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int result = 0; while (!queue.isEmpty()) { TreeNode curr = queue.poll(); // if this is leaf if (curr.left == null && curr.right == null) { result += curr.val; } if (curr.left != null) { curr.left.val = curr.val * 10 + curr.left.val; queue.add(curr.left); } if (curr.right != null) { curr.right.val = curr.val * 10 + curr.right.val; queue.add(curr.right); } } return result; }
129. 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. Example: Input: [1,2,3] 1 / \ 2 3 Output: 25 Explanation: The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path 1->3 represents the number 13. Therefore, sum = 12 + 13 = 25.
// recursive public TreeNode invertTree(TreeNode root) { if(root == null) return null; TreeNode leftNode = invertTree(root.left); TreeNode rightNode = invertTree(root.right); root.left = rightNode; root.right = leftNode; return root; } // iterative public TreeNode invertTree(TreeNode root) { if(root == null) return null; if(root.left == null && root.right == null) return root; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while(!queue.isEmpty()) { TreeNode curr = queue.remove(); TreeNode tmp = curr.left; curr.left = curr.right; curr.right = tmp; if(curr.right != null) { queue.add(curr.right); } if(curr.left != null) { queue.add(curr.left); } } return root; }
226. Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: This problem was inspired by this original tweet by Max Howell: Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a whiteboard so f*** off.
public int kthSmallest(TreeNode root, int k) { Stack<TreeNode> toExplore = new Stack<>(); // iterate all the way to the left while(root != null) { toExplore.push(root); root = root.left; } while(k != 0) { TreeNode curr = toExplore.pop(); k--; if(k == 0) return curr.val; // if k is still not 0 // go one right and iterate all the way left again TreeNode right = curr.right; while(right != null) { toExplore.push(right); right = right.left; } } return -1; }
230. Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements. Example 1: Input: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 Output: 1
Postorder traversal is used to delete the tree. Postorder traversal is also useful to get the postfix expression of an expression tree.
Why we use Postorder traversal?
public TreeNode deleteNode(TreeNode root, int key) { if(root == null) { return root; } if(key < root.val) { root.left = deleteNode(root.left, key); } else if(key > root.val) { root.right = deleteNode(root.right, key); } else { // found node to delete // case 1: no child if(root.left == null && root.right == null) { root = null; } // case 2: one child else if(root.left == null) { root = root.right; } else if(root.right == null) { root = root.left; } // case 3: two children else { TreeNode temp = minimum(root.right); root.val = temp.val; root.right = deleteNode(root.right, temp.val); } } return root; } private TreeNode minimum(TreeNode root) { while(root.left != null) { root = root.left; } return root; }
450. Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
public TreeNode insertIntoBST(TreeNode root, int val) { TreeNode z = new TreeNode(val); if (root == null) return z; treeInsert(root, z); return root; } private void treeInsert(TreeNode root, TreeNode z) { TreeNode x = root; TreeNode y = null; while (x != null) { y = x; if (z.val < x.val) { x = x.left; } else { x = x.right; } } // found the insert position if (y == null) { root = z; } else if (z.val < y.val) { y.left = z; } else { y.right = z; } }
701. You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
private TreeNode first; private TreeNode second; private TreeNode prev = new TreeNode(Integer.MIN_VALUE); public void recoverTree(TreeNode root) { // In order traversal to find the two elements traverse(root); // Swap the values of the two nodes int temp = first.val; first.val = second.val; second.val = temp; } private void traverse(TreeNode root) { if (root == null) return; traverse(root.left); if (prev != null && prev.val > root.val) { if (first == null) { // If first element has not been found, assign prev to it first = prev; } second = root; } prev = root; traverse(root.right); }
99. Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
public List<Integer> inorderTraversalIterative(TreeNode root) { Stack<TreeNode> stack = new Stack<>(); List<Integer> result = new ArrayList<>(); TreeNode current = root; while(current != null || !stack.isEmpty()) { if (current != null) { stack.push(current); current = current.left; } else { current = stack.pop(); result.add(current.val); current = current.right; } } return result; }
Give a nonrecursive algorithm that performs an inorder tree traversal.
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(!covers(root, p) || !covers(root, q)) return null; if(root == null || root == p || root == q) return root; boolean isPOnLeft = covers(root.left, p); boolean isQOnLeft = covers(root.left, q); if(isPOnLeft != isQOnLeft) return root; if(isPOnLeft) return lowestCommonAncestor(root.left, p, q); else return lowestCommonAncestor(root.right, p, q); } private boolean covers(TreeNode root, TreeNode p) { if(root == null) return false; if(root == p) return true; return covers(root.left, p) || covers(root.right, p); }
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)." Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5] _______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5 Example 1: Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6. Example 2: Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
public int maxDepth(TreeNode root) { if(root == null) return 0; return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); }
Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its depth = 3.
// Iterative solution public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new ArrayList<>(); if(root == null) return result; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while(queue.size() > 0){ //get size here int size = queue.size(); for(int i = 0; i < size; i++){ TreeNode top = queue.remove(); //the first element in the queue (right-most of the tree) if(i == 0){ result.add(top.val); } //add right first if(top.right != null){ queue.add(top.right); } //add left if(top.left != null){ queue.add(top.left); } } } return result; } // recursion public List<Integer> rightSideView(TreeNode root) { List<Integer> res = new ArrayList<>(); helper(root,0,res); return res; } void helper(TreeNode rt, int h, List<Integer> res){ if(rt == null) return; if(h >= res.size()) res.add(rt.val); helper(rt.right, h+1,res); helper(rt.left, h+1,res); }
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example: Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
public TreeNode search(TreeNode root, int k) { // Return a node with a given value k in the subtree rooted at root, // or null if no node with value k exists. if (root == null || k == root.val) { return root; } else if (k < root.val) { // if present, k must be in left subtree return search(root.left, k); } else { // if present, k must be in right subtree return search(root.right, k); } }
Implement search in binary search tree
public TreeNode successor(TreeNode root) { // Return the node in the subtree rooted at root with the smallest value greater than root's value. if (root.right != null) { return minimum(root.right); } // Find the lowest ancestor of root whose left child is also an ancestor of root. TreeNode y = root.parent; while (y != null && root == y.parent) { // continue up the tree root = y; y = y.parent; } return y; }
Implement successor in binary search tree
For each node, its left child's degree is -1 and is right child's degree is +1. We can do a level order traversal and save the degree information. public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if(root==null) { return result; } // level and list HashMap<Integer, List<Integer>> map = new HashMap<>(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); Queue<Integer> level = new LinkedList<Integer>(); queue.offer(root); level.offer(0); int minLevel = 0; int maxLevel = 0; while(!queue.isEmpty()) { TreeNode p = queue.poll(); int curr = level.poll(); //track min and max levels minLevel = Math.min(minLevel, curr); maxLevel = Math.max(maxLevel, curr); if (map.containsKey(curr)) { map.get(curr).add(p.val); } else { List<Integer> list = new ArrayList<Integer>(); list.add(p.val); map.put(curr, list); } if (p.left != null) { queue.offer(p.left); level.offer(curr - 1); } if (p.right != null) { queue.offer(p.right); level.offer(curr + 1); } } for(int i = minLevel; i <= maxLevel; i++) { if(map.containsKey(i)) { result.add(map.get(i)); } } return result; }
Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).
static ListNode h; public TreeNode sortedListToBST(ListNode head) { if (head == null) return null; h = head; int len = getLength(head); return sortedListToBST(0, len - 1); } // get list length public int getLength(ListNode head) { int len = 0; ListNode p = head; while (p != null) { len++; p = p.next; } return len; } // build tree bottom-up public TreeNode sortedListToBST(int start, int end) { if (start > end) return null; // mid int mid = (start + end) / 2; TreeNode left = sortedListToBST(start, mid - 1); TreeNode root = new TreeNode(h.val); h = h.next; TreeNode right = sortedListToBST(mid + 1, end); root.left = left; root.right = right; return root; }
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
The basic idea is here: Say we have 2 arrays, PRE and IN. Preorder traversing implies that PRE[0] is the root node. Then we can find this PRE[0] in IN, say it's IN[5]. Now we know that IN[5] is root, so we know that IN[0] - IN[4] is on the left side, IN[6] to the end is on the right side. Recursively doing this on subarrays, we can build a tree out of it :) Hope this helps. public TreeNode buildTree(int[] preorder, int[] inorder) { return helper(0, 0, inorder.length - 1, preorder, inorder); } public TreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) { if (preStart > preorder.length - 1 || inStart > inEnd) { return null; } TreeNode root = new TreeNode(preorder[preStart]); int inIndex = 0; // Index of current root in inorder for (int i = inStart; i <= inEnd; i++) { if (inorder[i] == root.val) { inIndex = i; } } root.left = helper(preStart + 1, inStart, inIndex - 1, preorder, inorder); root.right = helper(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder); return root; }
Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree: 3 / \ 9 20 / \ 15 7
O(n)
How long does it take to traverse an n-node binary search tree?
Because of the binary-search-tree property, you can print out all the keys in a binary search tree in sorted order by a simple recursive algorithm, called an inorder tree walk (inorder traversal).
How to print out all the keys in a binary search tree in sorted order?
public void inorderTraversal(TreeNode root) { if (root == null) return; inorderTraversal(root.left); System.out.println(root.val); inorderTraversal(root.right); }
Implement inorder traversal
public TreeNode searchIterative(TreeNode root, int k) { // Return a node with a given value k in the subtree rooted at root, // or null if no node with value k exists. while (root != null && k != root.val) { if (k < root.val) { // if present, k must be in the left subtree root = root.left; } else { // if present, k must be in the right subtree root = root.right; } } return root; }
Implement iterative search in binary search tree
public TreeNode maximum(TreeNode root) { // Return a node in subtree rooted at root with the largest value. while (root != null) { root = root.right; } return root; }
Implement maximum in binary search tree
public TreeNode minimum(TreeNode root) { // Return a node in subtree rooted at root with the smallest value. while (root.left != null) { root = root.left; } return root; }
Implement minimum in binary search tree
public void postOrderTraversal(TreeNode root) { if (root == null) return; preorderTraversal(root.left); preorderTraversal(root.right); System.out.println(root.val); }
Implement postorder traversal
public void preorderTraversal(TreeNode root) { if (root == null) return; System.out.println(root.val); preorderTraversal(root.left); preorderTraversal(root.right); }
Implement preorder traversal
public void topView(Node root) { if(root==null) return; Stack<Integer> s=new Stack<Integer>(); s.push(root.data); Node root2=root; while(root.left!=null) { s.push(root.left.data); root=root.left; } while(s.size()!=0) System.out.print(s.pop()+" "); Queue<Integer> q=new LinkedList<Integer>(); q.add(root2.right.data); root2=root2.right; while(root2.right!=null) { q.add(root2.right.data); root2=root2.right; } while(q.size()!=0) System.out.print(q.poll()+" "); }
Implement top view of BST
In a binary tree, if we consider null as leaves, then all non-null node provides 2 outdegree and 1 indegree (2 children and 1 parent), except root all null node provides 0 outdegree and 1 indegree (0 child and 1 parent). Suppose we try to build this tree. During building, we record the difference between out degree and in degree diff = outdegree - indegree. When the next node comes, we then decrease diff by 1, because the node provides an in degree. If the node is not null, we increase diff by 2, because it provides two out degrees. If a serialization is correct, diff should never be negative and diff will be zero when finished. public boolean isValidSerialization(String preorder) { String[] nodes = preorder.split(","); int diff = 1; for (String node: nodes) { // decrement indegree node by one diff--; if (diff < 0) return false; // increment outdegree node by two if (!node.equals("#")) diff += 2; } return diff == 0; } video: https://www.youtube.com/watch?v=_mbnPPHJmTQ
One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #. _9_ / \ 3 2 / \ / \ 4 1 # 6 / \ / \ / \ # # # # # # For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node. Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree. Each comma separated value in the string must be either an integer or a character '#' representing null pointer. You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3". Example 1: Input: "9,3,4,#,#,1,#,#,2,#,6,#,#" Output: true Example 2: Input: "1,#" Output: false
public List<TreeNode> deleteNodes(TreeNode root) { List<TreeNode> result = new ArrayList<>(); dfs(root, result, true); return result; } private void dfs(TreeNode root, List<TreeNode> result, boolean isRoot) { // if current root cannot be deleted and it is root, // then add to the result if (!shouldDelete(root) && isRoot) result.add(root); // check whether children should be roots isRoot = shouldDelete(root) if(root.left != null) { dfs(root.left, result, isRoot) if(shouldDelete(root.left)) root.left = null; } if(root.right != null) { dfs(root.right, result, isRoot); if(shouldDelete(root.right)) root.right = null; } }
We want to delete certain nodes from a binary tree. We have a function `shouldDelete(TreeNode node)` that returns true if we should delete that node, you can assume this function already exists. Write a function `deleteNodes(TreeNode root)` that takes a binary tree which removes the nodes that should be deleted from the tree and returns a forest of trees. A <- / \ B C / \ / \ D E F G
In addition to a key and satellite data, each node object contains attributes left, right, and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively. If a child or the parent is missing, the appropriate attribute contains the value NIL. The tree itself has an attribute root that points to the root node, or NIL if the tree is empty. The root node T.root is the only node in a tree T whose parent is NIL.
What is binary search tree?
The running time of TREE-SUCCESSOR on a tree of height h is O(h), since it either follows a simple path up the tree or follows a simple path down the tree.
What is the time complexity of the successor call on a tree of height h?
public int pathSum(TreeNode root, int sum) { if (root == null) return 0; return pathSumFrom(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); } private int pathSumFrom(TreeNode node, int sum) { if (node == null) return 0; return (node.val == sum ? 1 : 0) + pathSumFrom(node.left, sum - node.val) + pathSumFrom(node.right, sum - node.val); }
You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. Example: root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11
public int pathSum(TreeNode root, int sum) { if (root == null) return 0; return pathSumFrom(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); } private int pathSumFrom(TreeNode node, int sum) { if (node == null) return 0; return (node.val == sum ? 1 : 0) + pathSumFrom(node.left, sum - node.val) + pathSumFrom(node.right, sum - node.val); }
You are given a binary tree in which each node contains an integer value.Find the number of paths that sum to a given value.The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. Example:root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11