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:
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.