二叉树对称

 
  
package Struct;

public class TreeNode {
    public int val = 0;
    public TreeNode left = null;
    public TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }

    @Override
    public String toString() {
        return "TreeNode [val=" + val + ", left=" + left + ", right=" + right + "]";
    }
}
 
  

 

 1 package offer;
 2 
 3 import Struct.TreeNode;
 4 /**
 5  * 
 6  * 二叉树的镜像定义:源二叉树 
 7             8
 8            /  \
 9           6   10
10          / \  / \
11         5  7 9  11
12         
13    5 6 7 8 9 10 11
14         镜像二叉树
15             8
16            /  \
17           10   6
18          / \  / \
19         11 9 7   5
20    11 10 9 8 7 6 5    
21  * @author 爱不会绝迹
22  *
23  *
24  *    请实现一个函数,用来判断一颗二叉树是不是对称的。
25  *    注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
26  *
27  */
28 public class Problem38 {
29 
30     public static boolean isSymmetrical(TreeNode pRoot) {
31         if(pRoot==null){
32             return true;
33         }
34         return isMirror(pRoot.left,pRoot.right);
35     }
36     
37     public static boolean isMirror(TreeNode left,TreeNode right){
38         if(left==null&&right==null){
39             return true;
40         }
41         if(left==null || right==null){
42             return false;
43         }
44         return left.val==right.val&&isMirror(left.left,right.right)&&isMirror(left.right,right.left);
45     }
46     
47     private static int index = -1;
48     public static void main(String[] args) {
49         Integer[] array = {5,3,3,4,null,null,4,2,null,null,2,1,null,null,1};
50         TreeNode tree = createBinTree(array);
51         boolean b = isSymmetrical(tree);
52         System.out.println(b);
53     }
54     private static TreeNode createBinTree(Integer[] array) {
55         TreeNode tree = null;
56         if(index < array.length-1 && array[++index]!=null){
57             tree = new TreeNode(array[index]);
58             tree.left = createBinTree(array);
59             tree.right = createBinTree(array);
60         }
61         return tree;
62     }
63 }

 

转载于:https://www.cnblogs.com/yangenyu/p/11306868.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值