二叉树的先中后序遍历-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);
复制代码

 

本文作者:oaoa

本文链接:https://www.cnblogs.com/oaoa/p/14842243.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   喵喵队立大功  阅读(119)  评论(0编辑  收藏  举报
评论
收藏
关注
推荐
深色
回顶
收起
点击右上角即可分享
微信分享提示