0
点赞
收藏
分享

微信扫一扫

LeetCode-257-二叉树的所有路径

夏侯居坤叶叔尘 2021-09-28 阅读 72
LeetCode

二叉树的所有路径

解法一:递归法
import java.util.ArrayList;
import java.util.List;

public class LeetCode_257 {
    private static List<String> result = new ArrayList<>();

    public static List<String> binaryTreePaths(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        if (root.left == null) {
            binaryTreePaths(root.right, root.val + "");
        } else if (root.right == null) {
            binaryTreePaths(root.left, root.val + "");
        } else {
            binaryTreePaths(root.right, root.val + "");
            binaryTreePaths(root.left, root.val + "");
        }
        return result;
    }

    private static void binaryTreePaths(TreeNode root, String path) {
        if (root == null) {
            result.add(path);
            return;
        }
        if (root.left == null && root.right == null) {
            path += "->" + root.val;
            result.add(path);
        } else {
            path += "->" + root.val;
            if (root.left == null) {
                binaryTreePaths(root.right, path);
            } else if (root.right == null) {
                binaryTreePaths(root.left, path);
            } else {
                binaryTreePaths(root.right, path);
                binaryTreePaths(root.left, path);
            }
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.right = new TreeNode(5);

        for (String path : binaryTreePaths(root)) {
            System.out.println(path);
        }
    }
}
举报

相关推荐

0 条评论