LeetCode(53)-Binary Tree Paths

时间:2022-08-22 07:06:19

题目:

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5
All root-to-leaf paths are:

["1->2->5", "1->3"]

思路:

  • 题意:求二叉树根到叶子的所有路径
  • 二叉树的问题,没有一次递归解决不了的,如果有,那就两次,判断左右子树,都为空是叶子节点,否则一直递归下去,然后传入List参数和ArrayList参数

    -

代码:

public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> all = new ArrayList<String>();
        if(root == null){
            return all;
        }
        getTreePaths(all,new ArrayList<Integer>(),root);
        return all;
    }
    private void getTreePaths(List<String> result,List<Integer> tmp,TreeNode node){
        if(node == null){
            return;
        }else{
            tmp.add(node.val);
        }
        if(node.left == null && node.right == null){
            result.add(getString(tmp));
        }
        if(node.left != null){
            getTreePaths(result,new ArrayList(tmp),node.left);
        }
        if(node.right != null){
            getTreePaths(result,new ArrayList(tmp),node.right);
        }
    }
    private String getString(List<Integer> tmp){
        StringBuffer sb= new StringBuffer();
        if(tmp == null||tmp.isEmpty()){
            return null;
        }
        sb.append(tmp.get(0));
        for(int i = 1;i < tmp.size();i++){
            sb.append("->").append(tmp.get(i));
        }
        return sb.toString();
    }
}