【力扣】145、二叉树的后序遍历

145、二叉树的后序遍历

在这里插入图片描述
注:二叉树的后序遍历:左右根;

// 递归
var postorderTraversal = function (root){
	const arr = [];//新建一个数组;
	const fun = (node) =>{
		if(node){
			fun(node.left);
			fun(node.right);
			arr.push(node.val)
		}
	}
	fun(root);
	return arr;
}
// 非递归
var postorderTraversal = function(root){
	if(!root) return [];
	let arr = [];//新建一个数组;
	let stack = [root];//把整个节点抛进去;
	while (stack.length){//节点有长度的话,进入循环
		const o =stack.pop();//抛出栈道的最后一个元素并删除
		arr.unshift(o.val);//数组里放置抛出元素的值
		o.left && stack.push(o.left);
		o.right & stack.push(o.right);
	}
	return arr;
}

猜你喜欢

转载自blog.csdn.net/weixin_44806635/article/details/131525249