有一顆二叉樹,寫程式碼找出來從根節點到flag節點的最短路徑並列印出來,flag節點有多個。比如下圖這個樹中的6和14是flag節點,請寫程式碼列印8、3、6 和 8、10、14兩個路徑
pesudo code :
//廣度優先
findPathInNode(root,target)
make a queue
push [root,path] into queue
while queue is not empty
pop pairs
node = pairs[0]
path = pairs[1]
if node->left==target
return path[]=target
elseif node->right==target
return path[]=target
else
push [left,path[]=left] into queue
push [right,path[]=right] into queue
return []
//深度優先
findPathInNode(root,target)
findPathIn(root,target,rootPath=[root->val])
if node has no child and val not equal to target
return false
if node->val==target
return rootPath[]=node->val
else
res1 = findPathIn(left,target,rootPath[]=left->val)
res2 = findPathIn(right,target,rootPath[]=right->val)
if res1
return res1
if res2
return res2
return []
//二叉搜尋樹的情況
node = root
res=[]
while node is not leaf
if node==t
put node val into res
return res
if node>t
put node into res
node=node left
continue
if node<t
put node into res
node = node right
continue
return []
go的bfs實現 , 參考了之前寫的perfect squares
覆盤: 思維定式 , 想當然的認為只能把node推入佇列 , 不過想到了儲存parent到節點中, 其實也是可以解決的 , 最後是參考之前做的perfect squares 把pairs [node , path ]推入
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
RootPath []int
}
//bfs
func findPathInNode(root *TreeNode,target int ) []int{
q:=[]*TreeNode{}
root.RootPath = []int{root.Val}
q=append(q,root)
for len(q)!=0 {
node:=q[0]
q=q[1:]
if node.Left.Val==target {
return append(node.RootPath,target)
} else if node.Right.Val==target {
return append(node.RootPath,target)
} else {
node.Left.RootPath = append(node.RootPath,node.Left.Val)
q=append(q,node.Left)
node.Right.RootPath = append(node.RootPath,node.Right.Val)
q=append(q,node.Right)
}
}
return []int{}
}