本文共 1339 字,大约阅读时间需要 4 分钟。
给一棵二叉树,找出从根节点到叶子节点的所有路径。
可参考376题一起做
/*** Definition of TreeNode:* public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * }* }*/public class Solution { /** * @param root the root of the binary tree * @return all root-to-leaf paths */ public ListbinaryTreePaths(TreeNode root) { List list = new ArrayList (); if(root != null) { String temp = "" + root.val; findWay(list, temp, root); } return list; } private void findWay(List list, String way, TreeNode node) { if(node.left != null && node.right != null) { String copy = way.toString(); way = way + "->" + node.left.val; copy = copy + "->" + node.right.val; findWay(list, way, node.left); findWay(list, copy, node.right); } else if(node.left != null && node.right == null) { way = way + "->" + node.left.val; findWay(list, way, node.left); } else if(node.left == null && node.right != null) { way = way + "->" + node.right.val; findWay(list, way, node.right); } else { list.add(way); } }}
转载地址:http://oijgj.baihongyu.com/