LeetCode 101. Symmetric Tree
原题链接在这里:https://leetcode.com/problems/symmetric-tree/
题目:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
题解:
本题与Same Tree类似。这里比较是否symmetric, 也是用recursion, 需要写一个helper function, 递归调用,每次对称着比较.
Time Complexity: O(n), n是tree的node数目. Space: O(logn).
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public boolean isSymmetric(TreeNode root) { 12 if(root == null){ 13 return true; 14 } 15 return isSymm(root.left, root.right); 16 } 17 18 private boolean isSymm(TreeNode p, TreeNode q){ 19 if(p == null && q == null){ 20 return true; 21 } 22 if(p == null || q == null){ 23 return false; 24 } 25 return p.val == q.val && isSymm(p.left, q.right) && isSymm(p.right, q.left); 26 } 27 }
AC C++:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 bool isSymmetric(TreeNode* root) { 15 if(!root){ 16 return true; 17 } 18 19 return isSym(root->left, root->right); 20 } 21 22 bool isSym(TreeNode* p, TreeNode* q){ 23 if(!p && !q){ 24 return true; 25 } 26 27 if(!p || !q){ 28 return false; 29 } 30 31 return p->val == q->val && isSym(p->left, q->right) && isSym(p->right, q->left); 32 } 33 };