[145] 二叉树的后序遍历(28)

61 阅读1分钟

这个题之前写过,什么前中后都写过,但是都是理解不透彻,很多都是背的,现在过了2个月重新写,完全不会,下面这个是我之前看人家解析的代码,看着跟助教讲的不一样记录一下 image.png

一下助教的写法,跟之前我写的很类似, 关键地方我都备注了

var postorderTraversal = function (root) {
	// 第一步盘空
	if (!root) {
		return [];
	}

	// 第二步 定义两个变量 res为最后返回的结果 stack是要借助的栈
	const res = [];
	const stack = [root];
	// 第三部 关键while玄幻stack
	while (stack.length) {
		// 3.1 
		root = stack.pop();
		// 3.2 进循环先把刚才3.1pop()出来的值插到前面
		res.unshift(root.val);
		// 3.3 判断左右节点是否 有值 有值的话放入stack中 要先左后右 反了不对
		if (root.left) {
			stack.push(root.left)
		}
		if (root.right) {
			stack.push(root.right)
		}
	}
	return res;
};