Leetcode - Binary Tree Paths

My code:

import java.util.ArrayList;
import java.util.List;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List binaryTreePaths(TreeNode root) {
        List ret = new ArrayList();
        helper(root, "", ret);
        return ret;
    }
    
    private void helper(TreeNode root, String s, List ret) {
        if (root == null) {
            return;
        }
        else if (root.left == null && root.right == null) {
            if (s.length() == 0) {
                s = "" + root.val;
            }
            else {
                s = s + "->" + root.val;
            }
            ret.add(s);
        }
        else {
            helper(root.left, s + (s.length() == 0 ? "" + root.val : "->" + root.val), ret);
            helper(root.right, s + (s.length() == 0 ? "" + root.val : "->" + root.val), ret);
        }
    }
    
    public static void main(String[] args) {
        Solution test = new Solution();
        TreeNode t1 = new TreeNode(1);
        TreeNode t2 = new TreeNode(2);
        TreeNode t3 = new TreeNode(3);
        TreeNode t4 = new TreeNode(5);
        t1.left = t2;
        t1.right = t3;
        t2.right = t4;
        List ret = test.binaryTreePaths(t1);
        System.out.println(ret.toString());
    }
}

这道题目典型的用 dfs
然后答案里面说可以用 stringbuilder
自己写了下

My code:

import java.util.ArrayList;
import java.util.List;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List binaryTreePaths(TreeNode root) {
        List ret = new ArrayList();
        helper(root, new StringBuilder(), ret);
        return ret;
    }
    
    private void helper(TreeNode root, StringBuilder sb, List ret) {
        if (root == null) {
            return;
        }
        else if (root.left == null && root.right == null) {
            int len = sb.length();
            sb.append(len == 0 ? root.val : "->" + root.val);
            ret.add(sb.toString());
            sb.delete(len, sb.length());
        }
        else {
            int len = sb.length();
            sb.append(len == 0 ? root.val : "->" + root.val);
            helper(root.left, sb, ret);
            helper(root.right, sb, ret);
            sb.delete(len, sb.length());
        }
    }
}

reference:
https://discuss.leetcode.com/topic/23114/java-solution-using-stringbuilder-instead-of-string-manipulation

我觉得最巧妙的地方就在于, sb.delete(len, sb.length());
这就是 backtracking, 类似于 list.remove(list.size() - 1);

因为 stringbuilder 永远指向同一块内存,就是一个容器,和string不一样。所以省空间和时间的同时,一定得当心。

Anyway, Good luck, Richardo!

你可能感兴趣的:(Leetcode - Binary Tree Paths)