1 Title Description
Please implement a function, a binary tree is used to determine not symmetrical. Note that if a binary image is a binary tree with this same definition as symmetrical.
2 ideas and methods
Define a traversal algorithm, to then traverse right child node traversal left child node; symmetric, preorder: root -> right child node -> the left child node ; and preorder: root - > left child node -> right child node ; by comparison preorder traversal of a binary tree and symmetrical sequence preorder traversal to determine whether the binary tree is the same symmetry. Note meaning: Because the binary elements may all be the same, it will traverse during nullptr also taken into account.
3 C ++ core code
1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *right; 6 TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8 } 9 }; 10 */ 11 class Solution { 12 public: 13 bool isSymmetrical(TreeNode* pRoot) 14 { 15 return issymmetrical(pRoot,pRoot); 16 } 17 18 //Comparative binary tree preorder traversal sequence (Root -> Left -> right) and symmetric preorder sequence (Root -> Right -> left), if equal, symmetrical . 19 BOOL issymmetrical (the TreeNode * pRoot1, the TreeNode * pRoot2) { 20 is 21 is IF (pRoot1 == NULL && pRoot2 == NULL) 22 is return to true ; // since there may be a case where all the elements are equal; traversal sequence considered nullptr a 23 is 24 // a null pointer, another non-null pointer 25 IF (pRoot1 == NULL || pRoot2 == NULL) 26 is return to false ; 27 28 IF (pRoot1-> Val = pRoot2->! Val) 29 return to false ; 30 31 is return issymmetrical(pRoot1->right,pRoot2->left) && issymmetrical(pRoot1->left,pRoot2->right); 32 } 33 };
Reference material
https://blog.csdn.net/zjwreal/article/details/89282964