Traversing a n-ary tree without using recurrsion

What you are doing is essentially a DFS of the tree. You can eliminate recursion by using a stack: traverse(Node node) { if (node==NULL) return; stack<Node> stk; stk.push(node); while (!stk.empty()) { Node top = stk.pop(); for (Node child in top.getChildren()) { stk.push(child); } process(top); } } If you want a BFS use a queue: traverse(Node … Read more

Help me understand Inorder Traversal without using recursion

Start with the recursive algorithm (pseudocode) : traverse(node): if node != None do: traverse(node.left) print node.value traverse(node.right) endif This is a clear case of tail recursion, so you can easily turn it into a while-loop. traverse(node): while node != None do: traverse(node.left) print node.value node = node.right endwhile You’re left with a recursive call. What … Read more

Printing BFS (Binary Tree) in Level Order with Specific Formatting

Just build one level at a time, e.g.: class Node(object): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def traverse(rootnode): thislevel = [rootnode] while thislevel: nextlevel = list() for n in thislevel: print n.value, if n.left: nextlevel.append(n.left) if n.right: nextlevel.append(n.right) print thislevel = nextlevel t = Node(1, Node(2, Node(4, … Read more

How can I find the closest previous sibling with class using jQuery?

Try: $(‘li.current_sub’).prevAll(“li.par_cat:first”); Tested it with your markup: $(‘li.current_sub’).prevAll(“li.par_cat:first”).text(“woohoo”); <script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script> <ul> <li class=”par_cat”></li> <li class=”sub_cat”></li> <li class=”sub_cat”></li> <li class=”par_cat”>// this is the single element I need to select</li> <li class=”sub_cat”></li> <li class=”sub_cat”></li> <li class=”sub_cat current_sub”>// this is where I need to start searching</li> <li class=”par_cat”></li> <li class=”sub_cat”></li> <li class=”par_cat”></li> </ul> will fill up the closest … Read more