标签:对称树
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; } };
本文出自 “做最好的自己” 博客,请务必保留此出处http://qiaopeng688.blog.51cto.com/3572484/1835171
leetCode 101. Symmetric Tree 对称树
标签:对称树
原文地址:http://qiaopeng688.blog.51cto.com/3572484/1835171