LeetCode257—二叉树的所有路径(java版)

题目描述:

标签:树  深度优先搜索  

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

 代码:

思路分析:采用深度优先搜索(也就是遍历)前序遍历

判断是否添加到list中有:

①如果是叶子结点,则把路径添加到list中

②如果非叶子结点,则继续查找左子结点和右子结点路径

注意:这里定义了一个StringBuffer类,append()方法是添加元素。

StringBuffer => String : StringBuffer.toSring()

Integer => String : Integer.toString()

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> paths = new ArrayList<String>();
        constructPath(root,"",paths);
        return paths;
    }

    public void constructPath(TreeNode root,String path,List<String> paths){
        if(root != null){
            StringBuffer pathSB = new StringBuffer(path);
            pathSB.append(Integer.toString(root.val));
            if(root.left == null && root.right == null){
                paths.add(pathSB.toString());
            }else{
                pathSB.append("->");
                constructPath(root.left,pathSB.toString(),paths);
                constructPath(root.right,pathSB.toString(),paths);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40840749/article/details/115217775