Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
給一棵二元樹,請檢查它的鏡像是否和自己相等。(以中間為軸對稱)
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
null
的情況),再去比較它們的子樹。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isOpposite(TreeNode* left,TreeNode* right)
{
if(!left && !right) return true;
if(!left && right) return false;
if(left && !right) return false;
if(left->val != right->val) return false;
return isOpposite(left->left,right->right) && isOpposite(left->right,right->left);
}
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return isOpposite(root->left,root->right);
}
};
LeetCode
C++
1. Two Sum
Nov 15, 2023You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
Nov 15, 2023Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
Nov 9, 2023There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Nov 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up