二叉树的所有路径

86 阅读1分钟

二叉树的所有路径

代码如下

public class Solution {
    public List<String> data = new ArrayList<>();
    /**
     * @param root: the root of the binary tree
     * @return: all root-to-leaf paths
     */
    public List<String> binaryTreePaths(TreeNode root) {
        // write your code here
        if(root == null){
            return data;
        }
        childNode(root, String.valueOf(root.val));
        return data;
    }
    
    
    
    public void childNode(TreeNode root, String str){
        if(root.left != null){
            String left = str + "->" + root.left.val;
            childNode(root.left, left);
        }
        if(root.right != null){
            String right = str + "->" + root.right.val;
            childNode(root.right, right);
        }
        if(root.right == null && root.left == null){
            data.add(str);
        }
    }
}

通过递归不断下移左右节点,当一个节点的左右子节点都为空时,说明这个节点再没有分支,那么将该路径加入的List中去。

文采不好,大家见谅。