当前位置:网站首页>Enter an integer and a binary tree

Enter an integer and a binary tree

2022-07-25 03:01:00 Rookies also have dreams

 Enter an integer and a binary tree .  From the root node to the leaf node, all the nodes form a path .  Print out all paths equal to the input integer .  For example, enter an integer 22  And the following binary tree 

          10

        / \

       5  12

      / \

     4   7

 Then print out two paths :10, 12  and 10, 5, 7.

Using recursion + The method of backtracking

 Ideas :
 (1) If the value of the root node is greater than the given value or the root node is empty , Then clear the path ;
(2) If the value of the root node is equal to the given value , You need to determine whether the current node is a leaf node , If it's a leaf node , Is a path that needs to be found , Store in a stack . If it is not , Empty all the saved nodes .
(3) If the sum of the root nodes is less than the given value , Then visit the left and right subtrees respectively 
public class test4{
    public static class Node{
        private int value;
        private Node leftNode;
        private Node rightNode;

        public Node(int value,Node leftNode,Node rightNode){
            this.value = value;
            this.leftNode = leftNode;
            this.rightNode = rightNode;
        }
    }

    public  void findpath(Node node,int num){
        if (node.value > num || node == null){
            return;
        }
        // Use the stack to save the nodes on the path 
        Stack<Integer> s = new Stack<>();
         int currentsum = 0;
        findpath(node,num,s,currentsum);
    }

    public  void findpath(Node node,int num,Stack<Integer> s,int curretnsum){
        s.push(node.value);
        curretnsum += node.value;
        boolean isleaf = (node.leftNode == null && node.rightNode == null);
        // If the node is a leaf node , And the path and =sum
       if (curretnsum == num && isleaf){
           // Print path 
           printstack(s);
       }
       // If it's not a leaf node   Then traverse his nodes 
        if (node.leftNode != null){
            findpath(node,num,s,curretnsum);
        }
        if (node.rightNode !=null){
            findpath(node,num,s,curretnsum);
        }
       s.pop();
       curretnsum -= node.value;
    }
    public  void printstack(Stack<Integer> s){
        Stack<Integer> tem = new Stack<>();
        while (!s.isEmpty()){
            tem.add(s.pop());
        }while (!tem.isEmpty()){
            int num = tem.pop();
            System.out.println(num + "");
            s.add(num);
        }
    }

}
原网站

版权声明
本文为[Rookies also have dreams]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/202/202207200529227078.html