Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 二叉树到HTML列表_Javascript_Html_Binary Tree - Fatal编程技术网

Javascript 二叉树到HTML列表

Javascript 二叉树到HTML列表,javascript,html,binary-tree,Javascript,Html,Binary Tree,我有一个二叉树,我想转换成嵌套的HTML无序列表 我有一个函数,我正试图修改它来完成这项任务 我正在尝试以下方法(为输出运行代码段): 此方法位于BinaryTreeClass中 inOrderTraverseHtml(start = this.rootPtr) { if (!start.isLeaf()) { this.html+="<ul>" } else { this.html+="<li>"

我有一个二叉树,我想转换成嵌套的HTML无序列表

我有一个函数,我正试图修改它来完成这项任务

我正在尝试以下方法(为输出运行代码段):

此方法位于BinaryTreeClass中

inOrderTraverseHtml(start = this.rootPtr) {
    if (!start.isLeaf()) 
    {
        this.html+="<ul>"
    }
    else
    {
        this.html+="<li>"
    } // end if
    if (start.getLeftChild() !== null) 
    {
        this.inOrderTraverseHtml(start.getLeftChild());
    }; // end if
    this.html+=`<a href="#">${start.getItem().value}</a>`;
    if (start.getRightChild() !== null) 
    {
        this.inOrderTraverseHtml(start.getRightChild());
    }; // end if
    if (!start.isLeaf()) 
    {
        this.html+="</ul>"
    }
    else
    {
        this.html+="</li>"
    } // end if
} // end inOrderTraverseHtml  
正文{
高度:1000px;
}
  • Node类从第5行开始
  • 数学模型课从第45行开始
  • 二叉树类从第69行开始
    • toHTML()从第168行开始
    • toHTML()调用第182行的inordertraversethtml()
    • 这将从第302行的Draw事件的实现中调用
  • 抽象数据类型的实现从JS的第269行开始
  • 取消注释第307行以查看树
开始
  • 单击开始
  • 单击“绘制”

  • 开始 画
    因此我向BinaryNodeTree添加了一个类扩展。它在下面,按照我的需要工作

    class BinaryNodeTreeToHTML extends BinaryNodeTree {
        constructor(rootPtr, className = "tree-html") {
            super(rootPtr);
            this.html = [];
            this.rootPtr = rootPtr;
            this.className = className;
        }
        createContainer() {
            const _ = this;
            return new $("<div />", {
                "class": _.className
            });
        }
        createListItem(type, value, id, parentId) {
            const _ = this;
            return $("<li />", {
                id,
                "data-parent_id": parentId,
                "data-type": type,
                "data-value": value,
                html: _.createAnchor(type, value)
            });
        }
        createAnchor(type, value) {
            return $("<a />", {
                href: "#",
                "data-type": type,
                text: value
            });
        }
        createUnorderedList(parent = "root") {
            return $("<ul />", {
                "data-parent": parent
            })
        }
        Start(outputClassName) {
            const _ = this;
            console.log(this.Root);
            const $output = $(`.${outputClassName}`).eq(0);
            const $container = this.createContainer();
            let $main_ul = _.createUnorderedList();
            $container.append($main_ul);
            $output.append($container);
            console.log(_.html);
            this.inOrderTraverse((Item, Id, Pointer, Parent) => {
                if (Parent !== null) {
                    let $new_item = _.createListItem(Item.Type, Item.Value, Id, Parent.Id);
                    $main_ul.append($new_item);
                } else {
                    let $new_item = _.createListItem(Item.Type, Item.Value, Id, "root");
                    $main_ul.append($new_item);
                }
            })
            for(let obj of $main_ul.find("li")){
                let $obj = $(obj);
                if($obj.data().parent_id !== "root"){
                    let $parent = $("#"+$obj.data().parent_id);
                    if($parent.find("[data-parent="+$parent.attr("id")+"]").length > 0){
                        let $ul = $parent.find("[data-parent="+$parent.attr("id")+"]")
                        $ul.append($obj);
                    }else{
                        $parent.append(_.createUnorderedList($parent.attr("id")).append($obj))
                    }
                }
    
            }
    
            return $container;
        }
    };
    
    类BinaryNodeTreeToHTML扩展了BinaryNodeTree{
    构造函数(rootPtr,className=“树html”){
    超级(rootPtr);
    this.html=[];
    this.rootPtr=rootPtr;
    this.className=className;
    }
    createContainer(){
    常数=这个;
    返回新的$(“”{
    “类”:\u.className
    });
    }
    createListItem(类型、值、id、父id){
    常数=这个;
    返回$(“
  • ”{ 身份证件 “data-parent_id”:parentId, “数据类型”:类型, “数据值”:值, html:uux.createAnchor(类型、值) }); } createAnchor(类型、值){ 返回$(“”){ href:“#”, “数据类型”:类型, 文本:值 }); } createUnorderedList(parent=“root”){ 返回$(“
      ”{ “数据父项”:父项 }) } 开始(outputClassName){ 常数=这个; console.log(this.Root); const$output=$(`.${outputClassName}`).eq(0); const$container=this.createContainer(); 让$main_ul=u.createUnorderedList(); $container.append($main_ul); $output.append($container); console.log(u.html); this.inOrderTraverse((项、Id、指针、父项)=>{ 如果(父级!==null){ 让$new\u item=\u0.createListItem(item.Type,item.Value,Id,Parent.Id); $main_ul.append($new_item); }否则{ 让$new_item=u.createListItem(item.Type,item.Value,Id,“root”); $main_ul.append($new_item); } }) 对于(让$main_ul.find(“li”)的obj){ 设$obj=$(obj); if($obj.data().parent_id!=“root”){ 设$parent=$(“#”+$obj.data().parent_id); 如果($parent.find(“[data parent=“+$parent.attr(“id”)+”])。长度>0){ 让$ul=$parent.find(“[data parent=“+$parent.attr(“id”)+”])) $ul.附加($obj); }否则{ $parent.append(u.createUnorderedList($parent.attr(“id”)).append($obj)) } } } 退回$container; } };
  • 因此我向BinaryNodeTree添加了一个类扩展。它在下面,按照我的需要工作

    class BinaryNodeTreeToHTML extends BinaryNodeTree {
        constructor(rootPtr, className = "tree-html") {
            super(rootPtr);
            this.html = [];
            this.rootPtr = rootPtr;
            this.className = className;
        }
        createContainer() {
            const _ = this;
            return new $("<div />", {
                "class": _.className
            });
        }
        createListItem(type, value, id, parentId) {
            const _ = this;
            return $("<li />", {
                id,
                "data-parent_id": parentId,
                "data-type": type,
                "data-value": value,
                html: _.createAnchor(type, value)
            });
        }
        createAnchor(type, value) {
            return $("<a />", {
                href: "#",
                "data-type": type,
                text: value
            });
        }
        createUnorderedList(parent = "root") {
            return $("<ul />", {
                "data-parent": parent
            })
        }
        Start(outputClassName) {
            const _ = this;
            console.log(this.Root);
            const $output = $(`.${outputClassName}`).eq(0);
            const $container = this.createContainer();
            let $main_ul = _.createUnorderedList();
            $container.append($main_ul);
            $output.append($container);
            console.log(_.html);
            this.inOrderTraverse((Item, Id, Pointer, Parent) => {
                if (Parent !== null) {
                    let $new_item = _.createListItem(Item.Type, Item.Value, Id, Parent.Id);
                    $main_ul.append($new_item);
                } else {
                    let $new_item = _.createListItem(Item.Type, Item.Value, Id, "root");
                    $main_ul.append($new_item);
                }
            })
            for(let obj of $main_ul.find("li")){
                let $obj = $(obj);
                if($obj.data().parent_id !== "root"){
                    let $parent = $("#"+$obj.data().parent_id);
                    if($parent.find("[data-parent="+$parent.attr("id")+"]").length > 0){
                        let $ul = $parent.find("[data-parent="+$parent.attr("id")+"]")
                        $ul.append($obj);
                    }else{
                        $parent.append(_.createUnorderedList($parent.attr("id")).append($obj))
                    }
                }
    
            }
    
            return $container;
        }
    };
    
    类BinaryNodeTreeToHTML扩展了BinaryNodeTree{
    构造函数(rootPtr,className=“树html”){
    超级(rootPtr);
    this.html=[];
    this.rootPtr=rootPtr;
    this.className=className;
    }
    createContainer(){
    常数=这个;
    返回新的$(“”{
    “类”:\u.className
    });
    }
    createListItem(类型、值、id、父id){
    常数=这个;
    返回$(“
  • ”{ 身份证件 “data-parent_id”:parentId, “数据类型”:类型, “数据值”:值, html:uux.createAnchor(类型、值) }); } createAnchor(类型、值){ 返回$(“”){ href:“#”, “数据类型”:类型, 文本:值 }); } createUnorderedList(parent=“root”){ 返回$(“
      ”{ “数据父项”:父项 }) } 开始(outputClassName){ 常数=这个; console.log(this.Root); const$output=$(`.${outputClassName}`).eq(0); const$container=this.createContainer(); 让$main_ul=u.createUnorderedList(); $container.append($main_ul); $output.append($container); console.log(u.html); this.inOrderTraverse((项、Id、指针、父项)=>{ 如果(父级!==null){ 让$new\u item=\u0.createListItem(item.Type,item.Value,Id,Parent.Id); $main_ul.append($new_item); }否则{ 让$new_item=u.createListItem(item.Type,item.Value,Id,“root”); $main_ul.append($new_item); } }) 对于(让$main_ul.find(“li”)的obj){ 设$obj=$(obj); if($obj.data().parent_id!=“root”){ 设$parent=$(“#”+$obj.data().parent_id); 如果($parent.find(“[data parent=“+$parent.attr(“id”)+”])。长度>0){ 让$ul=$parent.find(“[data parent=“+$parent.attr(“id”)+”])) $ul.附加($obj); }否则{ $parent.append(u.createUnorderedList($parent.attr(“id”)).append($obj)) } } } 退回$container; } };
  • 我一直在思考这个问题。我很高兴你想出了适合你的办法。我还没试着通过你的代码。疗法
    const inorder = (fn, node) => 
      (node.left ? inorder(fn, node.left) : [])
      .concat(fn(node.val))
      .concat(node.right ? inorder(fn, node.right) : [])
    
    node(
      '+',
      18,
      node('*', 4, 6)
    )
    
    {
      val: "+",
      left: 18,
      right: {
        val: "*",
        left: 4,
        right: 6
      }
    }
    
    node(
      node('+'),
      node(18),
      node('*', node(4), node(6))
    )
    
    {
      val: {
        val: "+",
        left: undefined,
        right: undefined
      },
      left: {
        val: 18,
        left: undefined,
        right: undefined
      },
      right: {
        val: "*",
        left: {
            val: 4,
            left: undefined,
            right: undefined
        },
        right: {
            val: 6,
            left: undefined,
            right: undefined
        }
      }
    }
    
    const node = (val, left, right) => 
        Object.assign({val}, left ? {left} : {}, right ? {right} : {})
    
    {
      val: {
        val: "+"
      },
      left: {
        val: 18
      },
      right: {
        val: "*",
        left: {
          val: 4
        },
        right: {
          val: 6
        }
      }
    }
    
    const operator = (value) => ({type: 'op', value})
    const number = (value) => ({type: 'num', value})
    
    const myTree = node(
      operator('+'),
      node(
        operator('-'), 
        node(
          operator('/'),
          node(number(60)),
          node(number(75)),
        ),
        node(number(60))
      ),
      node(number(20))
    )
    
    const toHtml = (tree) => `<div class='tree'><ul>` + preorder(
      node => node.type === 'op' 
          ? `<li><a class="${node.type}" href="#">${node.value}</a><ul>` 
          : `<li><a class="${node.type}" href="#">${node.value}</a></li>`,
      node => node.type === 'op' 
          ? `</ul></li>` 
          : ``, 
      tree
    ).join('') + `</ul></div>`
    
    toHtml(myTree)
    
    <div class='tree'>
      <ul>
        <li>
          <a class="op" href="#">+</a>
          <ul>
            <li>
              <a class="op" href="#">-</a>
              <ul>
                <li>
                  <a class="op" href="#">/</a>
                  <ul>
                    <li>
                      <a class="num" href="#">60</a>
                    </li>
                    <li>
                      <a class="num" href="#">75</a>
                    </li>
                  </ul>
                </li>
                <li> 
                  <a class="num" href="#">60</a>
                </li>
              </ul>
            </li>
            <li>
              <a class="num" href="#">20</a>
            </li>
          </ul>
        </li>
      </ul>
    </div>