树的深度和广度遍历(JavaScript版)

来源:互联网 发布:青海干部网络教育 编辑:程序博客网 时间:2024/06/08 20:09

每一个树的节点元素为

node={data:"",left:"",right:""}

深度遍历:

void DepthFirstTravel(root)  {      var  stack=[];      stack.push(root);      while(stack.length>0)      {          root = stack.pop();          console.log(root.data);        if(root.rchild != "")          {             stack.push(root.rchild);          }          if(root.lchild != "")          {              stack.push(root.lchild);          }       }  }  

广度遍历:

void BreadthFirstTravel(root)  {      var  queue=[];      queue.push(root);      while(queue.length>0)      {          root = queue.shift();          console.log(root.data);          if(root.lchild != "")          {              queue.push(root.lchild);          }          if(root->rchild != "")          {              queue.push(rootrchild);          }      }  }  
原创粉丝点击