1.Maximum Depth of Binary
求二叉树的最大深度,递归解决。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
else {
int nLeft = maxDepth(root.left)+1;
int nRight = maxDepth(root.right)+1;
return nLeft > nRight ? nLeft : nRight;
}
}
}
2.Same Tree
求两棵二叉树是否完全一样
如果都为null则true,如果只有一个null则false,如果值不一样则false;否则判断左右结点是否都一样
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null)
return true;
if(p==null||q==null)
return false;
if(p.val!=q.val)
return false;
else
return isSameTree(p.left , q.left)&&isSameTree(p.right , q.right );
}
}