您好,登錄后才能下訂單哦!
101. Symmetric Tree
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
代碼如下:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //思路: //1.判斷root是否為空,若空則返回true,否則false; //2.判斷root->left,root->right是否同時(shí)為空,若為空則返回true; //3.判斷root->left,root->right同時(shí)不為空時(shí),將root->right反轉(zhuǎn), //然后判斷新root->right和root->left是否為相同的樹。 class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { bool childResult; if( NULL == p && NULL == q) return true; if( NULL != p && NULL != q && p->val == q->val) { return childResult = isSameTree(p->left,q->left) && isSameTree(p->right,q->right); } return false; } void reverseTree(TreeNode* root) { if(!root) return; TreeNode *p,*q; p = root->left; q = root->right; root->left = q; root->right = p; reverseTree(root->left); reverseTree(root->right); } bool isSymmetric(TreeNode* root) { if( (NULL == root) || ( NULL == root->left && NULL == root->right) ) return true; if(NULL != root->left && NULL != root->right) { reverseTree(root->right); return isSameTree(root->left,root->right); } return false; } };
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。