思路
- 最開始是用dfs的iteration做,遇到葉子節點就把treenode array裏面所有node的val生成string path。爲了實現DFS,所有的right child node都是在把left child node遍歷完之後(現在看這是錯的,錯的邏輯都要寫不下去了。。。)再加入到treenode array裏面。
- 這是錯的,有的節點沒有左子樹怎麼辦
- 這麼看左右子樹應該同等對待,這就需要一個flag告訴我們父節點是不是左右子樹都遍歷完了。如果都完了就可以層層向上刪除,如果沒有則遍歷右子樹。
- 這個flag有兩種做法,一個是生成與所給tree同樣結構的tree,只標記當前節點的子節點的遍歷情況。
- 另一個是在將要遍歷下一層的時候,在TreeNode Array裏面插入一個標記TreeNode,這個比較簡單,之前見過別人用。
- Recursive做
- 不需要flg標記了,可以優化string building process
- 精華是有了子樹才加“->”不然只加上tn.val
- String初始的時候只給一個
""
即可,但最好用stringBuilder更快
- 不需要flg標記了,可以優化string building process
- Recursive在同一個function裏面的技巧
- 用for循環來實現從for 追溯到葉子節點再從上至下打印path 也是不太懂????
TreeNode注意事項
- Cannot use
tnArray == null
to determine if is null or not. We should usetnArray.size() == 0
- LinkedList is a deque, which means not a Stack! We cannot use
add()
andpop()
together. Thepop()
is pop from the beginning, not the last. If we use the linkedlist, we treat it as the linkedlist. Otherwise, you can useStack<> tnArray = new LinkedList<>()
to initiate as a stack.