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

二叉树的前序遍历 #117

Open
louzhedong opened this issue Jan 5, 2019 · 0 comments
Open

二叉树的前序遍历 #117

louzhedong opened this issue Jan 5, 2019 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处 LeetCode 算法第144题

给定一个二叉树,返回它的 前序 遍历。

示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [1,2,3]

思路

递归遍历

解答

/**
 * @param {TreeNode} root
 * @return {number[]}
 */
function helper(root, res) {
  res.push(root.val);
  if (root.left) {
    helper(root.left, res);
  }
  if (root.right) {
    helper(root.right, res);
  }
}

var preorderTraversal = function (root) {
  if (!root) return null;
  var res = [];
  helper(root, res);
  return res;
};
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