問題:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
image.png
All root-to-leaf paths are:
["1->2->5", "1->3"]
大意:
給出一個二叉樹甚侣,返回所有從根節(jié)點到葉子節(jié)點的路徑晦攒。
比如給出下面這個二叉樹:
image.png
所有從根節(jié)點到葉子節(jié)點的路徑為:
["1->2->5", "1->3"]
思路:
這道題適合用遞歸阅畴,依次判斷有沒有左右葉子節(jié)點,分別去做遞歸橱脸,在遞歸中把遇到的節(jié)點值拼接到路徑字符串的最后,注意要拼接“->”這個內(nèi)容律适,直到?jīng)]有左右子節(jié)點后管怠,表示已經(jīng)到了葉子節(jié)點了,就可以終止了亏掀,把這條路徑的字符串添加到結果中去忱反。
代碼:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<String>();
if (root == null) return result;
String path = String.valueOf(root.val);
findPath(result, root, path);
return result;
}
public void findPath(List<String> list, TreeNode root, String path) {
if (root.left == null && root.right == null) {
list.add(path);
return;
}
if (root.left != null) {
StringBuffer pathBuffer = new StringBuffer(path);
pathBuffer.append("->");
pathBuffer.append(String.valueOf(root.left.val));
findPath(list, root.left, pathBuffer.toString());
}
if (root.right != null) {
StringBuffer pathBuffer = new StringBuffer(path);
pathBuffer.append("->");
pathBuffer.append(String.valueOf(root.right.val));
findPath(list, root.right, pathBuffer.toString());
}
}
}
合集:https://github.com/Cloudox/LeetCode-Record