Binary Tree Paths

来源:互联网 发布:csol由于网络设定问题 编辑:程序博客网 时间:2024/05/29 18:52
import java.util.LinkedList;import java.util.List;import java.util.Queue;/* * Given a binary tree, return all root-to-leaf paths.For example, given the following binary tree:   1 /   \2     3 \  5All root-to-leaf paths are:["1->2->5", "1->3"] * */public class Solution {public static void main(String[] args) {// TODO Auto-generated method stub}public List<String> binaryTreePaths(TreeNode root) {        List<String> list = new LinkedList<>();        if(root == null)        return list;        getPaths("", root, list);        return list;    }public void getPaths(String path,TreeNode root,List<String> list){if(root.left==null&&root.right==null)//is a leaf{path =  path + root.val;list.add(path);}path = path +root.val+"->";//normal nodeif(root.left!=null)//leftgetPaths(path, root.left, list);if(root.right!=null)//rightgetPaths(path, root.right, list);}}class TreeNode {    int val;    TreeNode left;    TreeNode right;    TreeNode(int x)     {     val = x;    }}

0 0
原创粉丝点击