題目描述
難度級別:簡單
給定一個二叉樹,返回所有從根節點到葉子節點的路徑。
說明:
葉子節點是指沒有子節點的節點。
示例:
輸入:
1
/ \
2 3
\
5
輸出: ["1->2->5", "1->3"]
解釋: 所有根節點到葉子節點的路徑爲: 1->2->5, 1->3
解題思路
廣度優先搜索
創建非子節點隊列queue,與非子節點路徑隊列path。當隊列queue中存在值時,依次將queue,path與出列,若當前元素無左右節點,則說明爲子節點,則直接向輸出隊列中添加路徑值,若不是,則將存在的節點添加至隊列尾部,路徑也拼接至路徑隊列尾部。
const binaryTreePaths = function(root) {
if (!root) return []
const res_path = []
const queue = [root]
const path = [root.val.toString()]
while(queue.length) {
const current_node = queue.shift()
const current_path = path.shift()
if (!current_node.left && !current_node.right) {
res_path.push(current_path)
}else{
if (current_node.left) {
queue.push(current_node.left)
path.push(current_path+"->"+current_node.left.val.toString())
}
if (current_node.right) {
queue.push(current_node.right)
path.push(current_path+"->"+current_node.right.val.toString())
}
}
}
return res_path
};
題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/valid-anagram/