题目
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7返回它的最大深度 3 。
解题思路
递归方程: f(n) = 0 n = null
f(n) = 1 + max(f(n左),f(n右))
代码实现
/**
* 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 reInt = 0; //返回值
// 1、如果根节点为空返回0。
if (root == null) {
return 0;
}
// 2、找到最大深度
int nLeft = maxDepth(root.left);
int nRight = maxDepth(root.right);
return (nLeft > nRight) ? (nLeft+1) : (nRight+1);
}
}
用递归的方法实现容易出现栈溢出问题,因此最好以非递归方式实现,找了一个非递归实现...
public int treeDepth2(BinaryTreeNode root)
{
if(root == null)
return 0;
BinaryTreeNode current = null;
LinkedList<BinaryTreeNode> queue = new LinkedList<BinaryTreeNode>();
queue.offer(root);
int cur,last;
int level = 0;
while(!queue.isEmpty())
{
cur = 0;//记录本层已经遍历的节点个数
last = queue.size();//当遍历完当前层以后,队列里元素全是下一层的元素,队列的长度是这一层的节点的个数
while(cur < last)//当还没有遍历到本层最后一个节点时循环
{
current = queue.poll();//出队一个元素
cur++;
//把当前节点的左右节点入队(如果存在的话)
if(current.left != null)
{
queue.offer(current.left);
}
if(current.right != null)
{
queue.offer(current.right);
}
}
level++;//每遍历完一层level+1
}
return level;
}
可以看到对于树想要使用非递归实现就要将树放入队列或栈等其他结构中。