一、题目内容 简单

给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。

示例1:

输入:root = [1,2,3,null,5] 输出:["1->2->5","1->3"] 8. 二叉树的所有路径(257) - 图1

示例2:

输入:root = [1] 输出:[“1”]

提示:

  • 树中节点的数目在范围 [1, 100] 内
  • -100 <= Node.val <= 100

    二、解题思路

    这道题目要求从根节点到叶子的路径,所以需要前序遍历,这样才方便让父节点指向孩子节点,找到对应的路径。
    前序遍历以及回溯的过程如图:image.png

三、具体代码

  1. /**
  2. * @param {TreeNode} root
  3. * @return {string[]}
  4. */
  5. var binaryTreePaths = function (root) {
  6. const path = []
  7. const result = []
  8. const backTracking = (node) => {
  9. if (!node) return
  10. path.push(node.val)
  11. if (!node.left && !node.right) {
  12. result.push(path.join('->'))
  13. return
  14. }
  15. if (node.left) {
  16. backTracking(node.left)
  17. path.pop()
  18. }
  19. if (node.right) {
  20. backTracking(node.right)
  21. path.pop()
  22. }
  23. }
  24. backTracking(root)
  25. return result
  26. };

四、其他解法

迭代法

我们可以依然可以使用前序遍历的迭代方式来模拟遍历路径的过程。
遍历过程中的注意事项:

  1. 先判断 node.right,再判断 node.left,这样方便做前序遍历
  2. paths 和 stack 的顺序保持一致。

image.png

  1. var binaryTreePaths = function (root) {
  2. const stack = [root]
  3. while (stack.length) {
  4. // 先从右节点开始,才能方便的前序遍历
  5. if (node.right) {
  6. stack.push(node.right)
  7. }
  8. if (node.left) {
  9. stack.push(node.left)
  10. }
  11. }
  12. return result
  13. };

完整代码如下:

  1. /**
  2. * @param {TreeNode} root
  3. * @return {string[]}
  4. */
  5. var binaryTreePaths = function (root) {
  6. const result = []
  7. if (!root) return result
  8. const stack = [root]
  9. const paths = [root.val]
  10. while (stack.length) {
  11. const node = stack.pop()
  12. const path = paths.pop()
  13. if (!node.left && !node.right) {
  14. const tmp = typeof path === 'string' ? path : '' + path
  15. result.push(tmp)
  16. }
  17. // 先从右节点开始,才能方便的前序遍历
  18. if (node.right) {
  19. stack.push(node.right)
  20. paths.push(path + '->' + node.right.val)
  21. }
  22. if (node.left) {
  23. stack.push(node.left)
  24. paths.push(path + '->' + node.left.val)
  25. }
  26. }
  27. return result
  28. };