简体   繁体   中英

print ancestor nodes in a binary tree for given input node without using recursion in java

How to get the ancestor nodes for a binary tree without recursion.I have the below code using recursion,but couldn't figure out on how to get without using recursion.

boolean printAncestors(Node node, int target) {        
    /* base cases */
    if (node == null) {
        return false;
    }

    if (node.data == target) {
        return true;
    }

    /* If target is present in either left or right subtree of this node then print this node */
    if (printAncestors(node.left, target) || printAncestors(node.right, target)) {
        System.out.print(node.data + " ");
        return true;
    }

    /* Else return false */
    return false;
}

One simple approach involves a "to-do list" of some sort, and a Map to keep track of ancestors. The to-do list could be a queue or a stack. The basic plan would be something like this:

  • Initialize the to-do list to contain just the root
  • While the to-do list is not empty:
    • Get the next node N from the to-do list
    • If N is your target, stop
    • If N.left is not null, add (N.left, N) to the "ancestors" map. This map will let you find the ancestor of any node that is visited.
    • If N.right is not null, add (N.right, N) to the "ancestors" map
    • If N.left is not null, add it to the to-do list
    • If N.right is not null, add it to the to-do list

At that point, the target's parent, grandparent, etc., all the way up the chain, will be in the "ancestors" map, so it should be easy to print all the ancestors.

If you use a stack for the to-do list, you should push N.right onto the stack before N.left . Then you will be traversing the tree in preorder.

If you use a queue for the to-do list, so that you add elements to the end and retrieve them from the beginning, then I think the traversal order will be a breadth-first search, in which we traverse the root, then all nodes on the next level, then all nodes on the level below that, etc.

This is the simplest answer I can think of, and it can provide a template for how to solve other tree-traversal problems without recursion. (Plus it works for other kinds of graphs, if you add logic to make sure you don't visit a node twice.) It's not the best answer in terms of space efficiency. With some thought, you could come up with an algorithm that doesn't use a Map , and that doesn't push both children of a node on the stack or queue (so that the maximum stack size will be smaller).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM