本文共 2177 字,大约阅读时间需要 7 分钟。
输出二叉树的寻叶路径
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"]
遍历二叉树的时候,每当寻到叶结点,把路径装进结果里
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 Listres = 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/