Binary Tree Paths

来源:互联网 发布:阿里云的产品好吗 编辑:程序博客网 时间:2024/06/06 08:52

这也成了基本功。。。。。。。

/** * 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<String> binaryTreePaths(TreeNode root) {        List<String> results = new ArrayList<String>();        if (root == null) {            return results;        }        helper(results, String.valueOf(root.val), root);        return results;    }        private void helper(List<String> results, String path, TreeNode root) {        if (root == null) {            return;        }        if (root.left == null && root.right == null) {            results.add(path);            return;        }        if (root.left != null) {            helper(results, path + "->" + String.valueOf(root.left.val), root.left);        }        if (root.right != null) {            helper(results, path + "->" + String.valueOf(root.right.val), root.right);        }    }        // public List<String> binaryTreePaths(TreeNode root) {    //     List<String> results = new ArrayList<String>();    //     if (root == null) {    //         return results;    //     }    //     //List<String> list = new ArrayList<String>();    //     StringBuilder sb = new StringBuilder();    //     helper(results, sb.append(root.val + "->"), root);    //     return results;    // }        // private void helper(List<String> results, StringBuilder sb, TreeNode root) {    //     if (root == null) {    //         return;    //     }    //     if (root.left == null && root.right == null) {    //         results.add(sb.substring(0, sb.length() - 2);    //         return;    //     }    //     helper(results, sb.a, root.left);    //     //list.remove(list.size() - 1);    //     helper(results, sb, root.right);    //     //list.remove(list.size() - 1);    // }}


0 0
原创粉丝点击