难度:中等
题目描述:
给定一个二叉树,返回它的后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
解题思路:
递归法:
var inorderTraversal = function(root) {
let result = [];
const pushRoot = (root) => {
if (root !== null) {
if (root.left !== null) {
pushRoot(root.left);
}
if (root.right !== null) {
pushRoot(root.right);
}
result.push(root.val);
}
};
pushRoot(root);
return result;
};
迭代法:
const postorderTraversal = (root) => {
const list = [];
const stack = [];
// 当根节点不为空的时候,将根节点入栈
if(root) stack.push(root)
while(stack.length > 0) {
const node = stack.pop()
// 根左右=>右左根
list.unshift(node.val)
// 先进栈左子树后右子树
// 出栈的顺序就变更为先右后左
// 右先头插法入list
// 左再头插法入list
// 实现右左根=>左右根
if(node.left !== null) {
stack.push(node.left)
}
if(node.right !== null) {
stack.push(node.right)
}
}
return list
}