Non-recursive algorithm:
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public:BOOLChecklist ( vector<int> List) {intn =List. Size (); for(intI=0; i<n;i++) {if(List[i]!=List[n-i-1])return false; }return true; }BOOLIssymmetric (TreeNode *root) {if(!root)return true; queue<pair<treenode*,int>> Q; vector<int> List;intPre =0; Q.push (pair<treenode*,int> (Root,1)); while(! Q.empty ()) {Pair<treenode *,int> P = q.front (); Q.pop ();if(P.second!=pre) {if(Checklist (List)==false)return false;List. Clear (); }if(P.first==null)List. Push_back (-1);Else List. push_back (P.first->val); Pre = P.second;if(P.first!=null) {if(P.first->left) Q.push (pair<treenode*,int> (P.first->left, (p.second+1)));ElseQ.push (pair<treenode*,int> (NULL, (p.second+1)));if(P.first->right) Q.push (pair<treenode*,int> (P.first->right, (p.second+1)));ElseQ.push (pair<treenode*,int> (NULL, (p.second+1))); } }return true; }};
Recursive algorithm:
/** * Definition forBinary tree * struct TreeNode {*intVal * TreeNode * Left; * TreeNode * Right; * TreeNode (intx): Val (x), Left(NULL), Right(NULL) {} * }; */classSolution { Public: BOOL Check (TreeNode * Left, TreeNode * Right) {if(! Left&&! Right) returntrue;if(( Left&&! Right)|| (! Left&& Right)|| ( Left->val!= Right->val)) returnfalse; Return (check ( Left- Left, Right- Right) &&check ( Left- Right, Right- Left)); } bool Issymmetric (TreeNode *root) {if(!root| | (!root-> Left&&!root-> Right)) returntrue; return Check (root-> Left,root-> Right); }};
Leetcode:symmetric Tree