二叉树的前序,中序,后序遍历

今天在做快手的笔试题,其中有道就我们判断一个满二叉树是否是平衡二叉树的问题,什么是平衡二叉树呢,就是为空树,或者左子树的所有值小于根节点,右子树所有值都大于根节点

思路:按中序遍历一遍二叉树,看是否升序,如果是就是平衡二叉树,否则就不是

binary_tree是每层按顺序输入的二叉树节点的值,是个数组

// 前序遍历
	function proRes(binary_tree, index) {
		let len = binary_tree.length;
		if(!len) return ;
		console.log(binary_tree[index]);
		if(index * 2 + 1 < len) {
			proRes(binary_tree, index * 2 + 1);
		}
		if(index * 2 + 2 < len) {
			proRes(binary_tree, index * 2 + 2);
		}
	}

// 中序遍历二叉树
	function midRes(binary_tree, index) {
		let len = binary_tree.length;
		if(!len) return ;
		if(index * 2 + 1 < len) {
			midRes(binary_tree, index * 2 + 1);
		}
		console.log(binary_tree[index]);
		if(index * 2 + 2 < len) {
			midRes(binary_tree, index * 2 + 2);
		}
	}
	
	// 后续遍历
	function postRes(binary_tree, index) {
		let len = binary_tree.length;
		if(!len) return ;
		if(index * 2 + 1 < len) {
			postRes(binary_tree, index * 2 + 1);
		}
		if(index * 2 + 2 < len) {
			postRes(binary_tree, index * 2 + 2);
		}
		console.log(binary_tree[index]);
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值