zoukankan      html  css  js  c++  java
  • [Algorithm] Binary tree: Level Order Traversal

    function Node(val) {
      return {
        val,
        left: null,
        right: null
      };
    }
    
    function Tree() {
      return {
        root: null,
        addLeft(val, root) {
          const newNode = Node(val);
          root.left = newNode;
          return newNode;
        },
        addRight(val, root) {
          const newNode = Node(val);
          root.right = newNode;
          return newNode;
        },
        levelOrder(root, visitFn) {
          const helper = (node, visitFn) => {
            if (node === null) {
              return;
            }
    
            const q = new Queue();
            q.push(node);
    
            while (!q.isEmpty()) {
              const current = q.peak();
              visitFn(current.val);
              current.left && q.push(current.left);
              current.right && q.push(current.right);
              q.pop();
            }
          };
    
          helper(root, visitFn);
        }
      };
    }
    
    function Queue() {
      return {
        nodes: [],
        push(val) {
          this.nodes.push(val); // O(1)
        },
        pop() {
          const [first, ...rest] = this.nodes;
          this.nodes = rest;
          return first;
        },
        peak() {
          return this.isEmpty() ? null : this.nodes[0];
        },
        isEmpty() {
          return this.nodes.length === 0;
        }
      };
    }
    
    /**
                   20
               
          14                28 
     
         
       10    15          24       32
    
       
    4    11            21         
    */
    
    const tree = new Tree();
    
    const n1 = Node(20);
    tree.root = n1;
    
    const n2 = tree.addLeft(14, n1);
    const n3 = tree.addRight(28, n1);
    
    const n4 = tree.addLeft(10, n2);
    tree.addRight(15, n2);
    
    const n5 = tree.addLeft(24, n3);
    tree.addRight(32, n3);
    
    tree.addLeft(4, n4);
    tree.addRight(11, n4);
    
    tree.addLeft(21, n5);
    
    tree.levelOrder(tree.root, x => console.log(x));
    //20,14,28,10,15,24,32,4,11,21
    

      

  • 相关阅读:
    MVC系列-7.更新
    MVC系列-6.注册页面
    MVC系列-5.详细信息
    MVC系列-4.布局页
    MVC系列-3.数据显示
    MVC系列-2.数据处理-登陆
    MVC系列-1.MVC入门
    bootstrap table 服务器端分页--ashx+ajax
    swift学习第八天:元组
    swift学习第七天:字典
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10692704.html
Copyright © 2011-2022 走看看