Re: [閒聊] 每日leetcode

作者: JIWP (JIWP)   2024-10-24 22:47:55
951. Flip Equivalent Binary Trees
給你兩棵二元樹
請問這其中一棵二元樹的一些節點經過flip operation後
會不會跟另外一棵二元樹相等
flip operation就是把一個node的左右節點交換
思路:
就把兩棵樹丟下去檢查
如果兩棵樹的node都為null為傳true
其中一個node為null或兩個node的值不相等回傳false
不是上面的情況
就接著檢查有flip operation 或是 沒有flip operation只要有一種情況是true
就回傳true
golang code :
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func flipEquiv(root1 *TreeNode, root2 *TreeNode) bool {
if root1 == nil && root2 == nil {
return true
}
if root1 == nil || root2 == nil || root1.Val != root2.Val {
return false
}
return (flipEquiv(root1.Left, root2.Right) && flipEquiv(root1.Right, root2.
Left)) || (flipEquiv(root1.Right, root2.Right) && flipEquiv(root1.Left, root2.
Left))
}

Links booklink

Contact Us: admin [ a t ] ucptt.com