symmetric Tree: Given a binary tree, check whether it is a mirror of the itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / 2 2/\/3 4 4 3
But the following are not:
1 / 2 2 \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
Test Instructions: Determine whether the binary tree is symmetrical.
idea: recursive method is used to judge two subtrees trees at the same time.
Code:
Public classSolution { Public Booleanissymmetric (TreeNode root) {if(root==NULL)return true; returnifsymmetric (root.left,root.right); } Public Booleanifsymmetric (TreeNode tree1,treenode tree2) {if(tree1==NULL&&tree2==NULL) return true; Else if(tree1==NULL|| tree2==NULL) return false; if(Tree1.val! =tree2.val)return false; Else return(Ifsymmetric (tree1.left,tree2.right) &&ifsymmetric (tree1.right,tree2.left)); }}
Leetcode (101): symmetric Tree