Sequentially traverse the tree in reverse preorder fashion

My goal is to locate the element that is positioned directly above another element in the layout. This could mean the element is nested within several levels of the DOM structure, or it may involve moving up a few levels in the hierarchy. For instance:

div.a        
  div.b      
    div.c      
    div.d    
      div.e  
        div.f
    div.g    
  div.h      
  div.i      
div.j        
div.k        

In this example, .b, .h, .i are immediate children of .a. So if I were to call getBefore($('.h'));, I would expect to receive .g. To achieve this, a pre-order reverse search would need to start at div.b.

The issue I'm encountering is that without a complete global recursive scan, it becomes challenging to handle situations like getBefore($('.c'));, where the expected result would be .b. The routine, without knowledge of the complete hierarchy, may mistakenly retrieve the bottom-most element .g after examining .b.

Considering this, it appears that a recursive implementation may not be a straightforward solution, as the routine does not receive the root node as input, but rather a node within a tree of unknown structure. In light of this, what would be a reasonable iterative approach? The DOM provides mechanisms to navigate to parent nodes, access previous siblings, and retrieve a list of child nodes for any given element.

Answer №1

To achieve the desired outcome, I utilized a unique approach. It involves employing a regular recursive preorder traversal function in conjunction with an iterative routine that is able to determine the appropriate direction to traverse.

The iterative routine begins by selecting a node and then navigating through the parent's sibling list using the node = node.previousSibling method. Once it reaches the top of the tree, it moves to the parent node by using node = node.parentNode. During each step of this process, a method is invoked that implements a standard recursive preorder search algorithm to locate the final relevant item in the node's rooted tree. For example, when accessing .g, it eventually leads to .f because $('.g')[0].previousSibling refers to .d which, in turn, contains .f.

Interestingly, when executing the getAfter() function to move in the forward direction, recursion is not necessary. Nevertheless, incorporating recursion does contribute to a more refined and elegant code structure.

Answer №2

One interesting concept in preorder traversal utilizing a stack is to prioritize pushing the right child before the left child. This ensures that the left child is processed before the right child.

class Node {
    int key;
    Node left, right;

    public Node() {}

    public Node(int key) {
        this.key = key;
    }
}

public List<Integer> iterativePreOrder() {
    List<Integer> list = new ArrayList<>();
    Stack<Node> nodeStack = new Stack<>();

    nodeStack.push(root);

    while (!nodeStack.empty()) {
         Node node = nodeStack.pop();
         list.add(node.key);

         if (null != node.right) nodeStack.push(node.right);
         if (null != node.left) nodeStack.push(node.left);
    }
    return list;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to manage rejections in async/await within the Array#map method

In my Node 8.1.2 project, I encountered a scenario where one file is calling another file's function within a map structure. While in a real example, I would normally use Promise.all on the map, that specific implementation is not the focus of this qu ...

Function that recursively checks for the existence of an ID within a nested object structure

I need assistance in developing a function that can determine whether the link ID of an object or any of its children match a specific ID. For instance, if the link ID for Product paths is 51125095, the function should return true when this ID is passed in ...

Stopping the setTimeout function triggered by a click event in a Reactjs application

I'm a beginner with Reactjs and I ran into a dilemma while using setTimeOut. I couldn't figure out whether to use clearTimeOut or stopPropagation() to stop it. Here's my code: render: function() { return ( < div className = "colorCl ...

Combining Repetitive Elements in an Array

Trying to combine an array of products with the same order_id while also including all objects from a second products array. Below are some sample orders: const orders = [ { "order_details": { }, "order_id": "1", ...

What is the process for creating a sub-menu for a dropdown menu item in Bootstrap 5?

https://i.sstatic.net/o4FLn.pngthis is my code which i have created this navigation bar with bootstrap and all of its drop downs but i want to add another drop down to the services drop down section inside of webdevelopment but it can't any easy solut ...

Finding the Modular Reciprocal with JavaScript

I am attempting to find the value of d by solving the equation ed ≡ 1 mod((p-1)(q-1)), similar to the RSA algorithm. Given e = 5 and (p-1)*(q-1) = 249996 I have experimented with various Javascript code snippets, such as: function calculateModInverse( ...

Transfer JSON data between controllers without utilizing Services or Factory in AngularJS during routing

On my Dashboard page, I have an Object. When a user clicks on the Details Page from the Dashboard, it should redirect to the Details page. I am looking to pass the JSON Object from the Dashboard Controller to the Details Controller. Is there a way to do ...

"How to automatically populate an input field with a value when the page loads in an

I need assistance with setting the input value to 1 when the page is loaded, but for some reason, it remains empty. Can someone help me troubleshoot this issue? <tr *ngFor="let item of cartItems; let i=index"> <td class="cart_pr ...

How can I preserve the line break in a textarea using PHP?

Is it possible to maintain line breaks in a textarea using PHP? Currently, I have a temporary solution that involves using the exec function to run a shell command, but I would prefer a purely PHP approach. Below is my temporary script - can you help me mo ...

Possible revised text: "Exploring methods for verifying elements within a div using Selenium

I have a situation where I need to verify elements within a div by using the following xpaths. The xpath for each item is as follows: Item 1:- //*[@id='huc-last-upsell-rows']/div[1]/div[2]/div[1]/div/div/a/img Item 2:- //*[@id='huc-last-u ...

Restrict the PHP generated Json response to display only the top 5 results

I need to modify my search bar so that it only displays the top 5 related products after a search. public function getProducts() { if (request()->ajax()) { $search_term = request()->input('term', ''); $locatio ...

An issue encountered with react-router-dom and the useLocation() function

Seeking guidance from experienced developers! I recently started using react-router-dom and encountered an issue with the useLocation() hook in my application. The error message states: "useLocation() may be used only in the context of a <Router> ...

"Using JavaScript to trigger a button click event, and then

I have a question that I think may sound silly, but here it is. I have this code snippet: <script type="text/javascript"> $(document).ready(function(){ var email_value = prompt('Please enter your email address'); if(email_value !== null){ ...

Ways to delete a particular query parameter from a URL in Next.js

http://localhost:3000/?search=test&type=abc&category=xyz When searching for "test" along with the type and category, the URL changes accordingly to the link provided above. return router.push( { pathname: `/`, query: { ...

I am encountering an issue with my authentication system where it is returning

I'm currently experiencing an issue with my authentication system using passport. For some reason, I keep getting an 'undefined' value returned. Can anyone provide assistance? Here is the code snippet in question: app.js passport.use(new L ...

Javascript's associative arrays: a versatile tool for data organization

Is there a way to achieve the same functionality in JavaScript as this PHP code?: $this->gridColumnData[] = array('field' => 'id', 'width' => 50, 'title' => 'Enquiry Id') ; $this->gridColumn ...

The scroll event listener activates based on the distance I have scrolled

const processChatRead = useCallback(() => { const chatWindow = refEntries.current; if ( chatWindow.scrollTop > chatWindow.scrollHeight - 800 && activeRoom && conversations?.content?.length > 0 && ...

What is the mechanism behind the operation of the inherits feature in Node.js?

The following code snippet illustrates how the inherits function works in node.js: exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, ...

Provide users with the option to select a specific destination for saving their file

In the midst of my spring MVC project, I find myself in need of implementing a file path chooser for users. The goal is to allow users to select a specific location where they can save their files, such as C:\testlocation\sublocation... Despite r ...

Refresh Form Following Submission

When using a react form that triggers a graphql mutation upon button click, the text entered in the form fields remains even after the mutation has been executed. This necessitates manual deletion of text for subsequent mutations to be run. Is there a way ...