获取二叉树中每条路径并存入

来源:互联网 发布:java线程池怎么关闭 编辑:程序博客网 时间:2024/06/10 10:57
import java.util.ArrayList;import java.util.List;/** *    1 *   /   \ *  2     3 *  /\ * 5  6 * 存入List  [1 2 5] [1,2,6] [ 1 3]  *  */public class BinaryTreePaths257 {    public List<String> binaryTreePaths(TreeNode root) {        List<String> answer = new ArrayList<String>();        if (root != null) searchBT(root, "", answer);        return answer;    }    private void searchBT(TreeNode root, String path, List<String> answer) {        if (root.left == null && root.right == null) answer.add(path + root.val);        if (root.left != null) searchBT(root.left, path + root.val + "-", answer);        if (root.right != null) searchBT(root.right, path + root.val + "-", answer);    }    private List<List<Integer>> getList(List<String> list) {        if (list == null) return null;        List<List<Integer>> result = new ArrayList();        for (String s : list) {            List<Integer> list1 = new ArrayList();            for (int k = 0; k < s.length(); k++) {                if (s.charAt(k) != '-') {                    list1.add(s.charAt(k) - '1' + 1);                }            }            result.add(list1);        }        return result;    }    public static void main(String[] args) {        TreeNode treeNode4=new TreeNode(6,null,null);        TreeNode treeNode3 = new TreeNode(5, null, null);        TreeNode treeNode2 = new TreeNode(3, null, null);        TreeNode treeNode1 = new TreeNode(2, treeNode3, treeNode4);        TreeNode treeNode = new TreeNode(1, treeNode1, treeNode2);        BinaryTreePaths257 m = new BinaryTreePaths257();        for (String s : m.binaryTreePaths(treeNode)) {            System.out.println(s);        }        m.getList(m.binaryTreePaths(treeNode));    }}

0 0
原创粉丝点击