leetcode:101 Symmetric Tree-每日編程第二十題

Symmetric Tree

Total Accepted: 83908 Total Submissions: 257485 Difficulty: Easy

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

思路:

1).還是得先判斷是否爲NULL,否則root->val就沒有意義。

2).接着定義一個重載函數isSymmetric(TreeNode* left,TreeNode* right),用來判斷left與right是否相等。不等返回false,相等則返回isSymmetric(left->right,right->left)&&isSymmetric(left->left,right->right)。即不斷遞歸,判斷每層是否對稱。

/**
 * 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 isSymmetric(TreeNode* left,TreeNode* right){
        if(left==NULL&&right==NULL){
            return true;
        }else if(left==NULL){
            return false;
        }else if(right==NULL){
            return false;
        }
        if(left->val==right->val){
            return (isSymmetric(left->left,right->right)&&isSymmetric(left->right,right->left));
        }else{
            return false;
        }
    }
    
    bool isSymmetric(TreeNode* root) {
        if(root==NULL){
            return true;
        }else{
            return isSymmetric(root->left,root->right);
        }
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章