[LeetCode]257. Binary Tree Paths

来源:互联网 发布:苏州收银软件sjzpos 编辑:程序博客网 时间:2024/06/05 04:47

题目描述: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中。否则继续递归遍历。

public List<String> binaryTreePaths(TreeNode root) {        List<String> answer = new ArrayList<String>();        if(root!=null)searchBT(root,"",answer);        return answer;    }    public 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);    }    class TreeNode{        TreeNode left;        TreeNode right;        int val;        public TreeNode(int x){            val = x;        }    }
原创粉丝点击