js 树 后序遍历的非递归方式

后序遍历是先遍历它的左右子树在遍历父节点,

主要用栈实现(先进后出)

例如一个树的对象:

const tree = [
  {
    id: 1,
    name: '张三',
    children: [
    	{
    		id: 2,
    		name: '李四',
    		children: [
    			{
    				id: 5,
    				name: '张五'
    			}
    		]
    	}
    ]
  },
  {
    id: 6,
    name: '玛丽'
  }
]

 后序遍历的非递归方式实现,出栈时需要判定它是否是叶子节点还有它的左右子树是否遍历完,当左右子树入栈时,同时把左右子树删除,出栈的判定方式是左右子树都不存在,这样的方式上述出栈的两种情况的判别条件就变成了一种,更加容易实现

function treeMap(tree){
	if(typeof tree !== "object"){
		return null;
	}
	array.push(tree[1]);
	array.push(tree[0]);
	while(array.length > 0){
		let curNode = array[array.length - 1];
		if(!curNode.children || curNode.children.length === 0){
			console.log(curNode.id,curNode.name);
			array.pop();
		}else{
			if(curNode.children[1]){
				array.push(curNode.children[1]);
				curNode.children.splice(1,1);
			}	
			if(curNode.children[0]){
				array.push(curNode.children[0]);
				curNode.children.splice(0,1);
			}
		}
	}
}
treeMap(tree);



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值