java二叉树的定义及求其最大深度&判断两棵二叉树是否相等

  1. 二叉树的定义
    代码如下:
public class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x){val=x;}
}
  1. 求二叉树的最大深度代码如下:
public class Solution{
    public int maxDepth(TreeNode root){
    if(root==null){
    return 0;
    }
    else{
    int left=maxDepth(root.left);
    int right=maxDepth(root.right);
    return 1+Math.math(left,right);
    }
    }
}
  1. 判断两棵二叉树是否相等的代码如下:
public class Solution{
    public boolean isSameTree(TreeNode p, TreeNode q){
    if(p==null||q==null) return p==q;
    return p.val==q.val&&isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
    }
}
posted @ 2018-09-06 07:34  wumh7  阅读(437)  评论(0编辑  收藏  举报