写在前面的话
二叉树遍历最基本的应用,求树的深度。
题目内容
给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数
返回二叉树深度3
1. 解法1
1.1 解题思路
求二叉树的深度,就是求左子树和右子树的深度,哪个更深就返回哪个的深度。
1.2 java实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
int leftDepth,rightDepth;//左右子树深度标记
if(root == null) return 0;
else{
leftDepth = maxDepth(root.left);
rightDepth = maxDepth(root.right);
return (leftDepth > rightDepth) ? (leftDepth+1):(rightDepth+1);//为左右子树深度赋值
}
}
}
1.3 时间复杂度分析
o(n)
结语
用到了递归以及三元运算,以及在return中进行赋值操作,此处技巧性较强,也可以拆开写。