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"]
给定一个二叉树,输出从根到叶子节点的路径。用递归来完成,代码如下:
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); } }
上一篇: 二叉树的先序遍历、中序遍历、后序遍历
下一篇: Bean 的四种构造方式
推荐阅读
-
Vue组件tree实现树形菜单
-
AngularJS递归指令实现Tree View效果示例
-
C# Serialization performance in System.Runtime.Serialization.Formatters.Binary.BinaryFormatter,Newtonsoft.Json.JsonConvert and System.Text.Json.JsonSe
-
MySQL:Unsafe statement written to the binary log using statement format since BI
-
BZOJ5462: [APIO2018] 新家(K-D Tree)
-
CF1204D Kirk and a Binary String
-
Webpack之tree-starking 解析
-
bitmap 索引和 B-tree 索引在使用中如何选择
-
Liunx系统命令中tree命令详解
-
linux采用binary方式安装mysql