LeetCode 101. Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).node

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:this

    1
   / \
  2   2
 / \ / \
3  4 4  3

 

But the following [1,2,2,null,3,null,3] is not:spa

    1
   / \
  2   2
   \   \
   3    3

 

Note:
Bonus points if you could solve it both recursively and iteratively.指針

 

 

解答:code

使用遞歸的方法最爲方便,每次傳入左右兩個節點的指針,首先判斷是否爲空,其次再判斷對應節點的數值是否相等,以及遞歸判斷左子樹的左子樹和右子樹的右子樹、左子樹的右子樹以及右子樹的左子樹blog

代碼以下:遞歸

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isSymmetric(TreeNode* root) {
13         return isMirror(root, root);
14     }
15     bool isMirror(TreeNode* left, TreeNode* right)
16     {
17         if (left == nullptr && right == nullptr)
18             return true;
19         if (left == nullptr || right == nullptr)
20             return false;
21         return (left->val == right->val) && isMirror(left->right, right->left) && isMirror(left->left, right->right);
22     }
23 };

 

時間複雜度:O(n),n爲節點數量,須要遍歷全部節點it

空間複雜度:O(n),遞歸的層數爲樹的深度,最差的狀況下節點的數量就是樹的高度,所以平均狀況爲線性複雜度io

相關文章
相關標籤/搜索