LeetCode_257. Binary Tree Paths

 

257. Binary Tree Paths

Easy

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

 

package leetcode.easy;

/**
 * Definition for a binary tree node. public class TreeNode { int val; TreeNode
 * left; TreeNode right; TreeNode(int x) { val = x; } }
 */
public class BinaryTreePaths {
	java.util.List<String> list = new java.util.LinkedList<>();

	public java.util.List<String> binaryTreePaths(TreeNode root) {
		path(root, "");
		return list;
	}

	private void path(TreeNode root, String str) {
		if (null == root) {
			return;
		}
		str = str + "->" + root.val;
		if (null == root.left && null == root.right) {
			list.add(str.substring(2));
			return;
		}
		path(root.left, str);
		path(root.right, str);
	}

	@org.junit.Test
	public void test() {
		TreeNode node11 = new TreeNode(1);
		TreeNode node21 = new TreeNode(2);
		TreeNode node22 = new TreeNode(3);
		TreeNode node32 = new TreeNode(5);
		node11.left = node21;
		node11.right = node22;
		node21.left = null;
		node21.right = node32;
		node22.left = null;
		node22.right = null;
		node32.left = null;
		node32.right = null;
		System.out.println(binaryTreePaths(node11));
	}
}

 

上一篇:2021年度编程语言排行榜来啦,它凭什么能超过C语言,排名第一?


下一篇:1155.Heap Paths-PAT甲级真题(DFS+堆和二叉树的概念)