题目描述:
给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
示例 1:
输入: root = [2,1,3] 输出: 1 示例 2:
输入: [1,2,3,4,null,5,6,null,null,7] 输出: 7
解法一:层序遍历求
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int findBottomLeftValue(TreeNode root) {
int result=0;
Queue<TreeNode> que=new LinkedList<>();
que.offer(root);
while(!que.isEmpty())
{
int size=que.size();
for(int i=0;i<size;i++)
{
TreeNode node=que.poll();
if(i==0)
{
result=node.val;
}
if(node.left!=null)
{
que.offer(node.left);
}
if(node.right!=null)
{
que.offer(node.right);
}
}
}
return result;
}
}
解法二:深度优先遍历——递归法
// 递归法
class Solution {
private int Deep = -1;
private int value = 0;
public int findBottomLeftValue(TreeNode root) {
value = root.val;
findLeftValue(root,0);
return value;
}
private void findLeftValue (TreeNode root,int deep) {
if (root == null) return;
if (root.left == null && root.right == null) {
if (deep > Deep) {
value = root.val;
Deep = deep;
}
}
if (root.left != null) findLeftValue(root.left,deep + 1);
if (root.right != null) findLeftValue(root.right,deep + 1);
}
}