您好,登錄后才能下訂單哦!
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是否同時為空,若為空則返回true; //3.判斷root->left,root->right同時不為空時,將root->right反轉, //然后判斷新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; } };
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。