Leetcode - 101. Symmetric Tree
解題思路
用recursive來將每個節點傳入並判斷他是否有左右節點且和他對應位置的節點內存的值是否相等
我滴程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
class Solution { public: bool isSymmetric(TreeNode* root) { if (root == NULL) { return true; } else { return sym(root->left, root->right); } } bool sym(TreeNode* left, TreeNode* right) { if (left == NULL && right == NULL) { return true; } else if (left == NULL || right == NULL) { return false; } else if (left->val != right->val) { return false; } else { return sym(left->left, right->right) && sym(right->left, left->right); } } };
|