如何使用JavaScript在树中查找节点

如何使用JavaScript在树中查找节点

本文介绍了如何使用JavaScript在树中查找节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有和object literal本质上是一个没有固定数量级别的树。我怎样才能在树中搜索特定节点,然后在javascript中以高效的方式返回该节点?

I have and object literal that is essentially a tree that does not have a fixed number of levels. How can I go about searching the tree for a particualy node and then return that node when found in an effcient manner in javascript?

基本上我有一个像这样的树并且会喜欢找到标题为'randomNode_1'的节点

Essentially I have a tree like this and would like to find the node with the title 'randomNode_1'

var data = [
{
title: 'topNode',
 children: [
   {
       title: 'node1',
       children: [
       {
           title: 'randomNode_1'
       },
       {
           title: 'node2',
           children: [
           {
               title: 'randomNode_2',
               children:[
               {
                   title: 'node2',
                   children: [
                   {
                       title: 'randomNode_3',
                   }]
               }
               ]
           }]
       }]
   }
  ]
 }];


推荐答案

根据@ Ravindra的回答得出这个答案,但是真正的递归。

Basing this answer off of @Ravindra's answer, but with true recursion.

function searchTree(element, matchingTitle){
     if(element.title == matchingTitle){
          return element;
     }else if (element.children != null){
          var i;
          var result = null;
          for(i=0; result == null && i < element.children.length; i++){
               result = searchTree(element.children[i], matchingTitle);
          }
          return result;
     }
     return null;
}

然后你可以打电话给它:

Then you could call it:

var element = data[0];
var result = searchTree(element, 'randomNode_1');

这篇关于如何使用JavaScript在树中查找节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:12