java 二叉树的路径

leetcode 题目链接

1. 题目考点

  1. String == 和 equals() 区别
  2. dfs 和 bfs 的变形

2. 考点解析

  1. == 比较两个变量所引用的对象的地址,equals() 比较的是两个对象的字面量
String s1 = "hello";
String s2 = "hello";
String s3 = s1;
String s4 = new String("hello");
s1 == s2 // true, 重用 "hello" 常量
s3 == s1 // true, 重用 "hello" 常量
s1 == s4 // false, s4 指向堆内存中的对象,对象地址不同
s1.equals(s4); // true, 字面量相同
  1. dfs 的变形,要用上一个函数的结果,需要添加一个参数,通过参数传递给下一个函数
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> paths = new ArrayList<String>();
        // dfs 的关键是添加两个参数,使用上一次函数的结果
        dfs(root, "", paths);
        return paths;
    }

    public void dfs(TreeNode root, String path, List<String> paths) {
        if (root != null) {
            StringBuffer pathSB = new StringBuffer(path);
            pathSB.append("" + root.val));
            if (root.left == null && root.right == null) {  // 当前节点是叶子节点
                paths.add(pathSB.toString());  // 把路径加入到答案中
            } else {
                pathSB.append("->");  // 当前节点不是叶子节点,继续递归遍历
                constructPaths(root.left, pathSB.toString(), paths);
                constructPaths(root.right, pathSB.toString(), paths);
            }
        }
    }
}
  1. bfs 的变形,结合额外的队列操作
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
      List<String> paths = new ArrayList<String>();
      if (root == null) return paths;
      Queue<TreeNode> nodeQ = new LinkedList<>();
      // 关键:添加额外的队列保存路径
      Queue<String> pathQ = new LinkedList<>();
      nodeQ.offer(root);
      pathQ.offer("" + root.val);
      while (! nodeQ.isEmpty()) {
        TreeNode node = nodeQ.poll();
        String path = pathQ.poll();
        if (node.left == null && node.right == null) paths.add(path);
        else {
          if (node.left != null) {
            nodeQ.offer(node.left);
            pathQ.offer(new String(path) + "->" + node.left.val);
          }
          if (node.right != null) {
            nodeQ.offer(node.right);
            pathQ.offer(new String(path) + "->" + node.right.val);
          }
        }
      }
      return paths;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值