[Leetcode]6.映象二叉樹判斷
阿新 • • 發佈:2021-10-21
請實現一個函式,用來判斷一棵二叉樹是不是對稱的。如果一棵二叉樹和它的映象一樣,那麼它是對稱的。
例如,二叉樹 [1,2,2,3,4,4,3] 是對稱的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面這個 [1,2,2,null,3,null,3] 則不是映象對稱的:
1
/ \
2 2
\ \
3 3
思想:遞迴判斷,判斷傳入的兩個結點是否為雙空或值相等,否則判false,如果為true,則傳入左結點的左孩子和右節點的右孩子,左節點的右孩子和右節點的左孩子繼續判斷.
主函式判斷根節點是否為空,並傳入根節點的左右孩子即可.
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func isSymmetric(root *TreeNode) bool { if root == nil{ return true } return test(root.Left,root.Right) } func test(l *TreeNode,r *TreeNode) bool{ if l==nil&&r==nil{ return true }else if l==nil||r==nil{ return false }else if l.Val!=r.Val{ return false } return test(l.Left,r.Right)&&test(l.Right,r.Left) }
題目來源:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof