Binary Tree based and path searching in the interview questions

Source: Internet
Author: User

Binary Tree is a type of Data Structure frequently used in interviews. It is very interesting to find a type of path. Currently, we have seen two types of questions: first, we need to provide a sum of the node values, and then we need to print the path that is equal to this.


1. Given a binary tree and a number, print all the root-to-leaf paths such that adding up all the values along the path equals the given number.


This question is relatively simple, because the requested path must be from the root node to the leaf node. Note that the binary tree mentioned here is not a binary search tree. In addition, if you encounter this question during the interview,First, you should ask the interviewer to determine whether the node value of the binary tree is positive.If the limit is positive, the algorithm can be effectively used for pruning. If the sum of the current path exceeds the target sum, you can stop searching.


When searching, record the desired node and current and in the current path.

There are two search cases:

1) when a leaf node is encountered: Check whether the path is equal to the target and the target. If it is equal, it is required;

2) Non-leaf nodes: recursively call the search function for the left and right branches.


@SuppressWarnings("unchecked")public static void findPaths(TreeNode root, int sum, int curSum,ArrayList
 
   path, ArrayList> paths) {if (root == null)return;path.add(root.val);curSum += root.val;// leaf nodeif (root.left == null && root.right == null) {if (curSum == sum) {paths.add(path);}}// non-leaf nodeelse {findPaths(root.left, sum, curSum, (ArrayList
  
   ) path.clone(),paths);findPaths(root.right, sum, curSum, path, paths);}}public static void main(String args[]) {TreeNode root = new TreeNode(10);root.left = new TreeNode(8);root.right = new TreeNode(2);root.left.left = new TreeNode(3);root.left.right = new TreeNode(5);root.right.left = new TreeNode(2);ArrayList
   
     path = new ArrayList
    
     ();ArrayList> paths = new ArrayList>();findPaths(root, 21, 0, path, paths);System.out.println(paths);path.clear();paths.clear();findPaths(root, 23, 0, path, paths);System.out.println(paths);path.clear();paths.clear();findPaths(root, 14, 0, path, paths);System.out.println(paths);}
    
   
  
 


In order to make the algorithms here have better applicability, we assume that there is not a positive number, and we hope to collect all the paths, rather than print them out when we encounter a desired path. Here, I put all the requested paths in a two-dimensional array linked list container.

Note that the clone function is used for path during recursive calling, which indicatesPass ValueInstead of passing references. In essence, we use the Backtracking Method to ensure that, even if the path is not found, the path will not be modified and the next recursive call in the same function will be affected. The time complexity is O (N * logN), because O (N) time is used for each node traversal. For each node, it takes O (logN) Time to pass the path or print the path.


2. You are given a binary tree in which each node contains a value Design an algorithm to print all paths which sum up to that value Note that it can be any path in the tree

-It does not have to start at the root.


It is still assumed that not all are positive numbers. However, this question may not be rigorous enough: do two top-down paths allow the intersection of the top-down paths and the merged path for any path? For example, if a binary tree with only three nodes and the root node has two or both child nodes, isn't the inverted vword path from the left child node to the right child node counted? Obviously, the situation will be more complicated if such a path needs to be considered. However, I have not considered this situation in my questions.
This question can still be expanded along the idea of the above question. If you encounter any node: 1) continue the current path and continue to add the current sum; 2) Start a new path from the left and right child nodes, and the current and cleared.


@SuppressWarnings("unchecked")public static void findPaths(TreeNode node, int sum, int curSum,ArrayList
 
   path, ArrayList> paths) {if (node == null) {return;}path.add(node.val);curSum += node.val;// the path can end with the current nodeif (sum == curSum) {paths.add(path);}// continue the current path, or start another path from the next nodeif (node.left != null) {// continue the current pathfindPaths(node.left, sum, curSum,(ArrayList
  
   ) path.clone(), paths);// start another new path from the left child nodefindPaths(node.left, sum, 0, new ArrayList
   
    (), paths);}if (node.right != null) {// continue the current pathfindPaths(node.right, sum, curSum,(ArrayList
    
     ) path.clone(), paths);// start another new path from the right child nodefindPaths(node.right, sum, 0, new ArrayList
     
      (), paths);}}
     
    
   
  
 

However, this exists during testing. RecurrenceTo generate redundant paths. The reason is that the same function interface is used for recursive calling of the current path extension and recursive calling of the new path. For example, if the input binary tree has at least three layers, two search branches are generated during root node search:

1.1) Try to allow the child node to continue the path starting from the root node;

1.2) try a new path starting with a subnode.

In subnode search, for Branch 1.1, two more search branches are generated:

2.1) Try to continue the path starting with the root node;

2.2) Try the new path starting from the Sun Tzu node.

For branch 1.2, two search branches are also generated:

2.3) Try to continue the path starting with the parent node;

2.4) Try the new path starting from the Sun Tzu node.


It can be found that branch 2.2 and 2.4 are exactly the same and belong to repeated recursion. The solution is to useTwo different search functions: One is responsible for searching all possible paths, and the other is only responsible for searching by continuing the current path.

public static void findPaths(TreeNode node, int sum,ArrayList
 
   path, ArrayList> paths) {if (node == null) {return;}// continue the current pathcontinueCurPath(node, sum, 0, path, paths);// start a new path from the next nodefindPaths(node.left, sum, new ArrayList
  
   (), paths);findPaths(node.right, sum, new ArrayList
   
    (), paths);}@SuppressWarnings("unchecked")public static void continueCurPath(TreeNode node, int sum, int curSum,ArrayList
    
      path, ArrayList> paths) {if (node == null) {return;}curSum += node.val;path.add(node.val);if (curSum == sum) {paths.add(path);}continueCurPath(node.left, sum, curSum,(ArrayList
     
      ) path.clone(), paths);continueCurPath(node.right, sum, curSum,(ArrayList
      
       ) path.clone(), paths);}public static void main(String args[]) {TreeNode root = new TreeNode(10);root.left = new TreeNode(8);root.right = new TreeNode(2);root.left.left = new TreeNode(3);root.left.right = new TreeNode(5);root.right.left = new TreeNode(2);root.left.right.left = new TreeNode(5);ArrayList
       
         path = new ArrayList
        
         ();ArrayList> paths = new ArrayList>();findPaths(root, 21, path, paths);System.out.println(paths);path.clear();paths.clear();findPaths(root, 23, path, paths);System.out.println(paths);path.clear();paths.clear();findPaths(root, 14, path, paths);System.out.println(paths);path.clear();paths.clear();findPaths(root, 5, path, paths);System.out.println(paths);}}
        
       
      
     
    
   
  
 


In the above Code, when the input target is set to 5, only two paths are returned. The Analysis of algorithm complexity is the same as that of the first question. It is still O (N * logN ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.