二叉树中根-叶节点路径(和)问题

记录二叉树中路径问题

1、打印所有从根节点-叶节点的路径
public void selectPaths(LinkedList<TreeNode> path, TreeNode node, List<List<TreeNode>> list) {
    if (node == null) {
      return;
    }
    path.add(node);
    if (node.left == null && node.right == null) {
      list.add(new ArrayList<>(path));
      return;
    }
    if (node.left != null) {
      selectPaths(path, node.left, list);
      path.removeLast();
    }
    if (node.right != null) {
      selectPaths(path, node.right, list);
      path.removeLast();
    }
  }

2、 二叉树中从根节点出发,是否存在路径和sum = target的问题?

  • 主要是涉及到返回值的问题
public boolean existsPath(LinkedList<TreeNode> path, TreeNode node, int sum, int target,
      List<List<TreeNode>> r) {
    if (path == null) {
      return false;
    }
    path.add(node);
    sum += node.val;

    if (node.left == null && node.right == null && sum == target) {
      r.add(new ArrayList<>(path));
      return true;
    }

    boolean left = false;
    if (node.left != null) {
      left = existsPath(path, node.left, sum, target, r);
      if (left) {
        return true;
      }
      path.removeLast();
    }
    boolean right = false;

    if (node.right != null) {
      right = existsPath(path, node.right, sum, target, r);
      if (right) {
        return true;
      }
      path.removeLast();
    }
    return false;
  }

3、打印从根节点-叶节点的路径和sum= 给定target的路径?

public void selectPaths(LinkedList<TreeNode> path, TreeNode node, List<List<TreeNode>> list,
      int sum, int target) {
    if (node == null) {
      return;
    }
    path.add(node);
    sum += node.val;
    if (node.left == null && node.right == null && sum == target) {
      list.add(new ArrayList<>(path));
      return;
    }
    if (node.left != null) {
      selectPaths(path, node.left, list, sum, target);
      path.removeLast();
    }
    if (node.right != null) {
      selectPaths(path, node.right, list, sum, target);
      path.removeLast();
    }
  }

总结

  • 1、关于路径和的问题,因为path是全局唯一的,所以回溯回来需要removeLast,但是sum为什么不需要sum-=node.val,因为sum+=node.val是在函数里面执行的,函数里面的sum不会影响到外面的sum。所以在回溯回来需要path.removeLast(),sum不需要-=;
  • 2、递归函数返回值的问题:如果需要遍历整个树则不需要返回值,否则需要返回值。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值