博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Binary Tree Paths
阅读量:6585 次
发布时间:2019-06-24

本文共 2177 字,大约阅读时间需要 7 分钟。

输出二叉树的寻叶路径

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

遍历二叉树的时候,每当寻到叶结点,把路径装进结果里

1 package com.rust.datastruct; 2  3 import java.util.ArrayList; 4 import java.util.List; 5  6 /** 7  * judging 8  * Binary Tree Paths 9  *10  * Given a binary tree, return all root-to-leaf paths.11  *12  * For example, given the following binary tree:13  *14  *   115  * /   \16  * 2    317  * \18  * 519  * All root-to-leaf paths are:20  * ["1->2->5", "1->3"]21  */22 class BinaryTreePathsSolution {23     List
res = new ArrayList
();24 public List
binaryTreePaths(TreeNode root) {25 if (root != null) track(root, root.val + "");/* String.valueOf(root.val)*/26 return res;27 }28 private void track(TreeNode n, String path){29 if (n.left == null && n.right == null) res.add(path);30 if (n.left != null) track(n.left, path + "->" + n.left.val);/* continue tracking */31 if (n.right != null) track(n.right, path + "->" + n.right.val);32 }33 }34 35 /**36 * Test main37 */38 public class BinaryTreePaths {39 public static void main(String args[]) {40 TreeNode root = new TreeNode(0);41 TreeNode node1 = new TreeNode(1);42 TreeNode node2 = new TreeNode(2);43 TreeNode node3 = new TreeNode(3);44 TreeNode node4 = new TreeNode(4);45 TreeNode node5 = new TreeNode(5);46 TreeNode node6 = new TreeNode(6);47 TreeNode node7 = new TreeNode(7);48 49 root.left = node1;50 root.right = node2;51 node1.left = node3;52 node1.right = node4;53 node2.left = node5;54 node2.right = node6;55 node4.right = node7;56 57 BinaryTreePathsSolution solution = new BinaryTreePathsSolution();58 List
res = solution.binaryTreePaths(root);59 60 for (int i = 0;i < res.size();i++){61 System.out.print(res.get(i) + " ");62 }63 System.exit(0);64 }65 66 }

输出:

0->1->3 0->1->4->7 0->2->5 0->2->6 

转载地址:http://cpano.baihongyu.com/

你可能感兴趣的文章
rabbitmq安装Management Plugin
查看>>
java中两个对象间的属性值复制,比较,转为map方法实现
查看>>
socket原理详解
查看>>
DpQuery.js
查看>>
Java 8 VM GC Tunning Guide Charter 7-8-b
查看>>
深入浅出JavaScript之闭包(Closure)
查看>>
【Todo】JS跨域访问问题的解决
查看>>
java Iterator Fail-fast机制
查看>>
Java堆外内存之五:堆外内存管理类ByteBuffer
查看>>
HTML5 input placeholder 颜色修改
查看>>
TJ/T808 终端通讯协议设计与实现(码农本色)
查看>>
URL传值中文乱码
查看>>
Mysql 乐观锁
查看>>
Spring MVC学习笔记——文件上传
查看>>
jmeter正则表达式
查看>>
分布式搜索引擎Elasticsearch的查询与过滤
查看>>
Struts2 XML配置详解
查看>>
C# mongodb $set或$addToSet批量更新很慢原因
查看>>
SolidEdge 工程图中如何给零件添加纹理或贴图
查看>>
Python3安装配置【转】
查看>>