c++ sort函式使用詳細指南
阿新 • • 發佈:2021-01-13
技術標籤:java演算法
題目 劍指 Offer 28. 對稱的二叉樹
請實現一個函式,用來判斷一棵二叉樹是不是對稱的。如果一棵二叉樹和它的映象一樣,那麼它是對稱的。
例如,二叉樹 [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
示例 1:
輸入:root = [1,2,2,3,4,4,3]
輸出:true
示例 2:
輸入:root = [1,2,2,null,3,null,3]
輸出:false
限制:
0 <= 節點個數 <= 1000
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
思路
分別中左右,中右左對樹遍歷
複雜度分析
時間:O(n)
空間: O(n)
程式碼
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null || (root.left == null && root.right == null)) {
return true;
}
if(root.left == null || root.right == null) {
return false;
}
return isSy(root.left, root.right);
}
boolean isSy(TreeNode root1, TreeNode root2) {
if(root1 == null && root2 == null) {
return true;
}
if(root1 == null || root2 == null) {
return false;
}
if(root1.val != root2.val) {
return false;
}
return isSy(root1.left, root2.right) && isSy(root1.right, root2.left);//分別中左右,中右左對樹遍歷
}
}