LeetCode题解:145. 二叉树的后序遍历,递归,JavaScript,详细注释
chencl1986 opened this issue · comments
原题链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
解题思路:
- 使用递归首先要思考,当前递归函数运行的是第n次递归,那么当前要做哪些处理。
- 先考虑的是,假设此时遍历到了最后一个节点为null,要给递归设置终止条件。
- 接下来要做的是遍历二叉树,即需要调用递归函数,继续遍历左节点和右节点。
- 本次递归还要处理当前节点的逻辑,即为存储当前节点的值,由于是后序遍历,存储时机为遍历左右节点之后。
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
function recursion(node, res) {
// 若节点为空,则退出
if (!node) {
return;
}
// 遍历左节点
recursion(node.left, res);
// 遍历右节点
recursion(node.right, res);
// 后续遍历,即为在开始遍历子节点之后,输出当前节点的值
res.push(node.val);
}
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function (root) {
let result = []; // 保存结果
// 递归遍历二叉树
recursion(root, result);
return result;
};