# LeetCode 101. Symmtric Tree ###### tags: `Leetcode` * 題目 Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). * 解法 * 判斷是否對稱的條件 1. 根節點val一樣 2. leftTree->left 要跟 rightTree->right對稱 3. leftTree->right 要跟 rightTree->left對稱 * 停止條件 1. leftTree == null && rightTree == null 左右都一樣是null代表對稱 2. leftTree == null || rightTree == null 左或右是null代表不對稱 ``` /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ //t1 = left tree, t2 = right tree bool isMirror(struct TreeNode* t1, struct TreeNode* t2) { if(!t1 && !t2) return true; if(!t1 || !t2) return false;//代表一邊有一邊沒有,所以不對稱 return (t1->val == t2->val)&&isMirror(t1->left, t2->right)&&isMirror(t1->right, t2->left); } bool isSymmetric(struct TreeNode* root){ if(!root) return true; return isMirror(root->left, root->right); } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up