513. 找树左下角的值
给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。假设二叉树中至少有一个节点。
在这里插入图片描述
- 思路分析:
- 先找出最深深度的叶子节点,然后在遍历左节点,最后遍历右节点
- 首先确定终止条件
if(root==null)//防止出现空指针异常
{
return;
}
if(root.right==null&&root.left==null)//当遍历到叶子节点
{
if(deep>max)//找出最大值
{
max=deep;
value=root.val;
}
}
- 先遍历左子树,在遍历右子树,因为找的是最左节点
if(root.left!=null)
{
deep++;
t(root.left,deep);
deep--;//在找最大深度时注意回溯的过程
}
if(root.right!=null)
{
deep++;
t(root.right,deep);
deep--;//在找最大深度时注意回溯的过程
}
- 完整的代码如下
if(root==null)
{
return;
}
if(root.right==null&&root.left==null)
{
if(deep>max)
{
max=deep;
value=root.val;
}
}
if(root.left!=null)
{
deep++;
t(root.left,deep);
deep--;
}
if(root.right!=null)
{
deep++;
t(root.right,deep);
deep--;
}