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.
Solution: recursive
1 public static boolean isSymmetrical(TreeNode pRoot){ 2 if(pRoot==null){ 3 return true; 4 } 5 return isSymmetrical(pRoot.left,pRoot.right); 6 } 7 public static boolean isSymmetrical(TreeNode left,TreeNode right){ 8 if(left==null&&right==null){ 9 return true; 10 } 11 if(left==null||right==null){ 12 return false; 13 } 14 if(left.val==right.val){ 15 return true; 16 } 17 return isSymmetrical(left.left,right.right)&&isSymmetrical(left.right,right.left); 18 }
Initialization tree:
1 public static class TreeNode{ 2 int val=0; 3 TreeNode left=null; 4 TreeNode right=null; 5 public TreeNode(int val){ 6 this.val=val; 7 } 8 } 9 private static List<TreeNode> nodeList = null; 10 public static TreeNode createBinTree(int[] array) { 11 = the nodeList new new the LinkedList <TreeNode> (); 12 is // the value in the array in turn converted to TreeNode node 13 is for ( int nodeIndex = 0; nodeIndex <be array.length; nodeIndex ++ ) { 14 nodeList.add ( new new TreeNode (Array [ nodeIndex])); 15 } 16 // establish lastParentIndex-1 before the parent of node a digital relationship with the child node of the parent node of a binary tree . 17 for ( int parentIndex = 0; parentIndex <be array.length / 2 -. 1; parentIndex ++ ) { 18 // left child 19 nodeList.get (parentIndex) .left = nodeList 20 is .get (parentIndex. 1 * 2 + ); 21 is // right child 22 is nodeList.get (parentIndex) .right = the nodeList 23 is .get (parentIndex * 2 + 2 ); 24 } 25 // last parent node: as the final a parent node may not be the right child, so separate out handle 26 is int lastParentIndex be array.length = / 2 -. 1 ; 27 // left child 28 nodeList.get (lastParentIndex) .left = the nodeList 29 .get (lastParentIndex. 1 + 2 * ); 30 // right child, if the length of the array is odd only establish the right child 31 if (array.length % 2 == 1) { 32 nodeList.get(lastParentIndex).right = nodeList 33 .get(lastParentIndex * 2 + 2); 34 } 35 return nodeList.get(0); 36 }
test:
1 public static void main(String[] args) { 2 int[] tree={8,6,6,5,7,7,5}; 3 TreeNode pRoot = createBinTree(tree); 4 boolean symmetrical = isSymmetrical(pRoot); 5 System.out.println(symmetrical); 6 } 7 输出: true