Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:144. 二叉树的前序遍历,递归,JavaScript,详细注释 #168

Open
chencl1986 opened this issue Sep 21, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/

解题思路:

  1. 使用递归首先要思考,当前递归函数运行的是第n次递归,那么当前要做哪些处理。
  2. 先考虑的是,假设此时遍历到了最后一个节点为null,要给递归设置终止条件。
  3. 接下来要做的是遍历二叉树,即需要调用递归函数,继续遍历左节点和右节点。
  4. 本次递归还要处理当前节点的逻辑,即为存储当前节点的值,由于是前序遍历,存储时机为遍历左右节点之前。
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
function recursion(node, res) {
  // 若节点为空,则退出
  if (!node) {
    return;
  }

  // 前序遍历,即为在开始遍历子节点之前,输出当前节点的值
  res.push(node.val);
  // 遍历左节点
  recursion(node.left, res);
  // 遍历右节点
  recursion(node.right, res);
}
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function (root) {
  let result = []; // 保存结果
  // 递归遍历二叉树
  recursion(root, result);

  return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant