LeetCode-101-對稱二叉樹

題目

給定一個二叉樹,檢查它是否是鏡像對稱的。

 

例如,二叉樹 [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

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/symmetric-tree
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

思路

這個題用遞歸其實很簡單,拿來記錄的原因是,看評論區看到一個點:

若在isSymmetric方法中調用isMirror(root, root)時,會多算一倍。

代碼

class Solution {
            public boolean isSymmetric(TreeNode root) {
	    	if (root == null) return true;
	    	return isMirror(root.left, root.right);
	    }
	    
	    private boolean isMirror(TreeNode left, TreeNode right){
	    	if (left == null && right == null) return true;
	    	if (left == null || right == null) return false;
	    	if (left.val == right.val) return isMirror(left.left, right.right)&& isMirror(left.right, right.left);
	    	return false;
	    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章