How is Backtracking done using recusrion in Binary Tree

删除回忆录丶 提交于 2019-12-21 02:35:41

问题


I'm trying to insert a Binary Node. My code is convoluted and there's no hope of rescuing it so I plan to rewrite it (basically I didn't account for backtracking and didn't think about the algorithm all that closely).

I'm trying to insert a Binary Node using in order traversal, but I don't understand how I'm supposed to backtrack.

     D
    / \
   B   E 
  / \ / \
 A  C F 

How would I search through the left subtree of root D and then go back and search through the right one? It might be a stupid question, but I'm stumped. The best I can come up with is something like this:

 if (!root.hasLeftChild) {
      root = root.getLeftChild(); 
      recurse(root); 
 } 

But when I reach the bottom, I can't go back up with the root. Also, it doesn't solve the problem where if I reach the bottom left node I have to fill up both children of that node before starting to backtrack.

I think I'm thinking about this the wrong way.


回答1:


Tree :

     D
    / \
   B   E 
  / \ / \
 A  C F 

For recurse :

Using InOrder Traverse

  if (root == null) 
    return;

      recurse(root.getLeftChild()); 
      int rootData = root.getData();
      recurse(root.getRightChild()); 

Now, how it recurses :

root.getLeftChild() will go on calling the left sub-child recursively unless it hits null node ( so control wont go to recurse(root.getRightChild()); unless null node is hit )

Tree traveled so far :

         D
        / 
       B    
      / 
     A  
    /
  null <-- current Position

So once it reaches node A, A.left == null, so it recurses back to node A (assigning value of node to rootData)

     D
    / 
   B
  / 
 A  <-- current Position

and after this, it goes to next recursive call, recurse(root.getRightChild());

         D
        / 
       B    
      / 
     A  
      \
      null <-- current Position

and now, since left and right of A have been traversed, control will go back to node B (which called b.left = A) and will look for B.right


Take this Stack for example, for below tree ( node , value )

     A
    / \
   B   E 
  / \ / \
 C  D F 

Steps :

  • A calls its left B, so A pushed in stack
  • B calls its left C, so B pushed in stack
  • C calls its left null, so C pushed in stack
  • Now C has both left and right as null...so this marks the end of recursion for this node, hence its popped out of Stack
  • Now, C is traversed completely, so, as B called C , control goes back to B and check which line called this command
  • As b.left was executed, it will now go to B.right and push D...... and this goes on , this is called Recursion Stack



回答2:


So you are trying to do a depth first search - which you can find in any number of books or on wikipedia.

They key, essentially, is that your function recursively calls itself on each child. e.g:

public Node findSpot(Node node, List<Node> visits){
    visits.add(node);
    //condition check, return this node if its the right node.
    Node result = null;
    for(Node child : node.getListChildren()){
        if((result findSpot(child)) != null){
             return result
        }
    }
    return null;
}

So this recursively checks down the nodes, putting a new method on the stack for each layer of depth in the tree. It then checks the next branch if it doesnt find what its looking for. The list of visits will let you see in what order it visits the nodes, so you can look. THis will help you understand how it works.




回答3:


Try this example. It visits all nodes in order by using recursion:

public class Example {

    public static void main(String[] args) {
        visitInOrder(new Node("D",
            new Node("B", new Node("A"), new Node("C")),
            new Node("F", new Node("E"))));
    }

    public static void visitInOrder(Node node) {
        if (node != null) {
            visitInOrder(node.left());
            System.out.println(node.name());
            visitInOrder(node.right());
        }
    }
}

class Node {

    private final String name;
    private Node left;
    private Node right;

    public Node(String name) {
        this(name, null);
    }

    public Node(String name, Node left) {
        this(name, left, null);
    }

    public Node(String name, Node left, Node right) {
        this.name = name;
        this.left = left;
        this.right = right;
    }

    public String name() { return name; }    

    public Node left() { return left; }

    public Node right() { return right; }
}

OUTPUT:

A
B
C
D
E
F


来源:https://stackoverflow.com/questions/23059127/how-is-backtracking-done-using-recusrion-in-binary-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!