[Algorithm] Binary tree: Level Order Traversal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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

  

posted @   Zhentiw  阅读(262)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-04-11 [Tailwind] Extending Tailwind with Responsive Custom Utility Classes
2018-04-11 [Tailwind] Control What Variations are Generated for Each Utility Class Module in Tailwind
2016-04-11 [RxJS] Creation operator: of()
点击右上角即可分享
微信分享提示