题目描述:输入一颗二叉树,求出该树的深度。(知识迁移能力)
思路:如果一棵树只有一个节点,则其深度为1,如果根节点只有左子树而没有右子树,则树的深度应该是左子树的深度加1,如果根节点只有右子树而没有左子树,则树的深度应该是右子树的深度加1,如果既有左子树又有右子树,则深度应该是左右子树的深度的较大值加1.可以采用递归的方式实现。
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
int depLeft;
int depRight;
if(root == null){
return 0;
}else{
depLeft = TreeDepth(root.left);
depRight = TreeDepth(root.right);
if(depLeft>depRight){
return depLeft+1;
}else{
return depRight+1;
}
}
}
}