leetcode 101、對稱二叉樹

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

例如,二叉樹 [1,2,2,3,4,4,3] 是對稱的。
在這裏插入圖片描述
但是下面這個 [1,2,2,null,3,null,3] 則不是鏡像對稱的:
在這裏插入圖片描述


思路:

簡單粗暴。滿足鏡像該有的3個條件直接返回。

/**
 * 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) {
        return check(root, root);
    }
    
    private boolean check(TreeNode lroot, TreeNode rroot) {
        if (lroot == null && rroot == null) return true;
        if (lroot == null || rroot == null) return false;
        return lroot.val == rroot.val && check(lroot.right, rroot.left) && check(lroot.left, rroot.right);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章