LeetCode:Binary Tree Paths

来源:互联网 发布:中文域名管理中心 编辑:程序博客网 时间:2024/04/29 11:39

问题描述:

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"]

思路:

简单的二叉树遍历,遍历的过程中记录之前的路径,一旦遍历到叶子节点便将该路径加入结果中。

JAVA代码:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {        List<String> res = new ArrayList<String>();        public List<String> binaryTreePaths(TreeNode root) {        if(root != null){            findpath(root,String.valueOf(root.val));//一个string参数转换为Integer类型        }        return res;    }    private void findpath(TreeNode n,String path){        if(n.left == null && n.right == null){            res.add(path);        }        if(n.left != null){            findpath(n.left,path + "->" + n.left.val);        }        if(n.right != null){            findpath(n.right,path + "->" + n.right.val);        }        }}


0 0
原创粉丝点击