这个是常见的对二叉树的操作。总结一下:
数的结构:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
1.二叉树深度
这个可以使用递归,分别求出左子树的深度、右子树的深度,两个深度的较大值+1即可。
package niuke.easy;
public class GetMaxDepth {
public static void main(String[] args) {
}
public int TreeDepth(TreeNode pRoot) {
if (pRoot == null)
return 0;
int leftDepth = TreeDepth(pRoot.left);
int rightDepth = TreeDepth(pRoot.right);
return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
}