题目大意:给定一个二叉树,计算出它的深度。
理解分析:题目指出深度是从根节点到叶子节点的一条最长路径。本方法采用后序遍历法,利用节点中的val来记录该节点的最大深度。最后根节点中存放的就是该二叉树的最大深度。
实现:
/**
* 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;
maxDepth(root.left);
maxDepth(root.right);
if(root.left == null && root.right == null) {
root.val = 1;
} else if(root.left != null && root.right != null) {
if(root.left.val > root.right.val)
root.val = root.left.val + 1;
else
root.val = root.right.val + 1;
} else if(root.left != null) {
root.val = root.left.val + 1;
} else
root.val = root.right.val + 1;
return root.val;
}
}