【Leetcode】257. 二叉树的所有路径

192 阅读1分钟

题目描述

在这里插入图片描述

题解

能用String解决的最好不要走StringBuilder。递归时注意空结点(null)回退和叶子结点判定回退。

执行用时:9 ms, 在所有 Java 提交中击败了30.66%的用户

内存消耗:39.1 MB, 在所有 Java 提交中击败了5.11%的用户

通过测试用例:208 / 208


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    List<String> res = new ArrayList<>();
    
    public List<String> binaryTreePaths(TreeNode root) {
        if (root == null)
            return res;
        recur(root, "");
        return res;
    }
    
    public void recur(TreeNode root, String path) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            res.add(path + root.val);
            return;
        }
        recur(root.left, path + root.val + "->");        
        recur(root.right, path + root.val + "->");
        return;
    }
}

反面教材:

通过测试用例:206 / 208

如果StringBuilder的话会非常麻烦,还要把加进去的string主动删掉,而且最后如果root.val数字长度不可预测,你根本不知道要删多少位。所以如果是这样还不如用一个List<String>来装path。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    List<String> res = new ArrayList<>();
    
    public List<String> binaryTreePaths(TreeNode root) {
        if (root == null)
            return res;
        recur(root, new StringBuilder());
        return res;
    }
    
    public void recur(TreeNode root, StringBuilder path) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            res.add(path.append(root.val).toString());
            path.delete(path.length() - 1, path.length());
            return;
        }
        recur(root.left, path.append(root.val + "->"));
        path.delete(path.length() - 3, path.length());
        recur(root.right, path.append(root.val + "->"));
        path.delete(path.length() - 3, path.length());
        return;
    }
}