欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Binary Tree Paths

程序员文章站 2022-07-10 10:38:16
...
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"]

给定一个二叉树,输出从根到叶子节点的路径。用递归来完成,代码如下:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> list = new ArrayList<String>();
        if(root == null) return list;
        getPath(root, String.valueOf(root.val), list);
        return list;
    }
    public void getPath(TreeNode root, String s, List<String> list) {
        if(root.left == null && root.right == null)
            list.add(s);
        if(root.left != null)
            getPath(root.left, s + "->" + root.left.val, list);
        if(root.right != null)
            getPath(root.right, s + "->" + root.right.val, list);
    }
    
}
相关标签: 二叉树