二叉树的先中后序遍历-JS递归实现

 

 1 const bt = {
 2     val: 1,
 3     left: {
 4         val: 2,
 5         left: {
 6             val: 4,
 7             left: null,
 8             right: null,
 9         },
10         right: {
11             val: 5,
12             left: null,
13             right: null,
14         },
15     },
16     right: {
17         val: 3,
18         left: {
19             val: 6,
20             left: null,
21             right: null,
22         },
23         right: {
24             val: 7,
25             left: null,
26             right: null,
27         },
28     },
29 };
30 //先序遍历
31 const preorder = (root) => {
32     if(!root) {return;}
33     console.log(root.val);
34     preorder(root.left);
35     preorder(root.right);
36 };
37 
38 preorder(bt);
39 
40 //中序遍历
41 const inorder = (root) => {
42     if(!root) {return;}
43     inorder(root.left);
44     console.log(root.val);
45     inorder(root.right);
46 };
47 inorder(bt);
48 
49 //后序遍历
50 const postorder = (root) => {
51     if(!root) {return;}
52     postorder(root.left);
53     postorder(root.right);
54     console.log(root.val);
55 };
56 
57 postorder(bt);

 

二叉树的先中后序遍历-JS递归实现

上一篇:JS 反射机制及 Reflect 详解


下一篇:mac big sur升级后启动nginx ,php52,php56,php71 脚本