LeetCode OJ 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"]

遞歸的方法:

public List<String> binaryTreePaths(TreeNode root) {
    List<String> answer = new ArrayList<String>();
    if (root != null) 
       searchBT(root, "", answer);
    return answer;
}
private void searchBT(TreeNode root, String path, List<String> answer) {
    if (root.left == null && root.right == null) 
        answer.add(path + root.val);//並沒有將path的值改變掉
    if (root.left != null) 
        searchBT(root.left, path + root.val + "->", answer);//同理,沒有將path的值改變掉,因爲後面可能要用到這個值
    if (root.right != null) 
        searchBT(root.right, path + root.val + "->", answer);
}

發佈了61 篇原創文章 · 獲贊 114 · 訪問量 42萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章