Lettcode_257_Binary Tree Paths
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]
Ideas:
(1) give a tree and find all the paths from the root to the leaf node.
(2) The question is actually the depth-first traversal of the tree. This article uses recursive methods to solve the problem. Starting from the root node, if the left subtree is not empty, the left subtree is traversed. If the left subtree is not empty, traverse the left child. Otherwise, traverse the right child ..... until the last leaf node is traversed. If you use a non-recursive algorithm, you need to set a stack to store the Left and Right Subtrees. This is also a good implementation.
(3) For details, see the code below. I hope this article will help you.
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
binaryTreePaths(TreeNode root) {List
result = new ArrayList
();if (root != null) {getpath(root, String.valueOf(root.val), result);}return result;}private static void getpath(TreeNode root, String valueOf,List
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);}}}