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
The code is as follows:
1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One Public Booleanissymmetric (TreeNode root) { A if(root==NULL) - return true; -TreeNode left=Root.left; theTreeNode right=Root.right; - - if(Lefttraverse (left). Equals (Righttraverse (right))) - return true; + - return false; + } A PublicList<string>lefttraverse (TreeNode root) { atList<string> list=NewArraylist<>(); - if(root==NULL) - returnlist; - - List.add (string.valueof (Root.val)); - if(root.left!=NULL) in List.addall (Lefttraverse (Root.left)); - Else toList.add (""); + - if(root.right!=NULL) the List.addall (Lefttraverse (root.right)); * Else $List.add ("");Panax Notoginseng returnlist; - } the PublicList<string>righttraverse (TreeNode root) { +List<string> list=NewArraylist<>(); A if(root==NULL) the returnlist; + - List.add (string.valueof (Root.val)); $ if(root.right!=NULL) $ List.addall (Righttraverse (root.right)); - Else -List.add (""); the - if(root.left!=NULL)Wuyi List.addall (Righttraverse (Root.left)); the Else -List.add (""); Wu - About returnlist; $ } -}
101. Symmetric Tree