其他分享
首页 > 其他分享> > 二叉树的先中后序遍历-JS非递归实现

二叉树的先中后序遍历-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 //可以用堆栈来模拟递归
32 
33 //先序遍历
34 const preorder = (root) => {
35     if(!root) {return; }
36     const stack = [root];  //创建一个栈
37     while (stack.length) {
38         const n = stack.pop();
39         console.log(n.val);  
40         if(n.right) stack.push(n.right); //根左右,栈是后进先出,所以先把右结点压栈
41         if(n.left) stack.push(n.left);
42     }
43 }
44 preorder(bt)
45 
46 //中序遍历
47 const inorder = (root) => {
48     if(!root) {return; }
49     const stack = [];  //创建一个栈
50     let p = root;
51     while(stack.length || p) {
52         while(p) {      
53             stack.push(p); //左根右,遍历所以左结点压入栈中
54             p = p.left;
55         }
56         const n = stack.pop();
57         console.log(n.val); //弹出就是 左结点和中结点
58         p = n.right; //把右结点压入,参与循环
59     }
60 }
61 
62 inorder(bt);
63 
64 //后序遍历
65 const postorder = (root) => {    //后序遍历是左 右 根,先序遍历得到的是根 左 右
66     if(!root) {return; }  // 把前序遍历的顺序调换一下得到 根 右 左,压栈再弹出就变成了 左 右  根
67     const outputStack = [];
68     const stack = [root];  //需要两个栈
69     while (stack.length) {
70         const n = stack.pop();
71         outputStack.push(n);
72         if(n.left) stack.push(n.left);
73         if(n.right) stack.push(n.right);
74     }
75     while(outputStack.length) {  //倒叙输出即可
76         const n = outputStack.pop();
77         console.log(n.val);
78     }
79 }
80 
81 postorder(bt);

 

标签:right,const,val,JS,二叉树,先中,root,stack,left
来源: https://www.cnblogs.com/oaoa/p/14842902.html