Leetcode_257_Binary Tree Paths

来源:互联网 发布:淘宝网买家地域解读 编辑:程序博客网 时间:2024/06/03 21:31

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/49432057



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)题意为给定一棵树,找出所有从根到叶子节点的路径。

(2)该题实为树的深度优先遍历。本题是使用递归的方法来进行求解的,从根节点开始,若左子树不为空,则遍历左子树,若左子树的左孩子不为空,则遍历左孩子,否则遍历右孩子.....直到遍历完最后一个叶子节点为止。使用非递归算法,则需要设定一个栈来保存左右子树,也很好实现,这里不累赘了。

(3)详情见下方代码。希望本文对你有所帮助。


package leetcode;import java.util.ArrayList;import java.util.List;import leetcode.utils.TreeNode;public class Binary_Tree_Paths {public static void main(String[] args) {TreeNode r = new TreeNode(1);TreeNode r1 = new TreeNode(2);TreeNode r2 = new TreeNode(3);TreeNode r3 = new TreeNode(5);r.left = r1;r.right = r2;r1.right = r3;binaryTreePaths(r);}public static List<String> binaryTreePaths(TreeNode root) {List<String> result = new ArrayList<String>();if (root != null) {getpath(root, String.valueOf(root.val), result);}return result;}private static void getpath(TreeNode root, String valueOf,List<String> result) {if (root.left == null && root.right == null)result.add(valueOf);if (root.left != null) {getpath(root.left, valueOf + "->" + root.left.val, result);}if (root.right != null) {getpath(root.right, valueOf + "->" + root.right.val, result);}}}


1 0
原创粉丝点击