给定一棵二叉树,要求寻找其最下面一层的最左边叶子。
分析:可以用队列进行从右至左的层级遍历,队列最后一个节点就是最左下的节点。也可以用递归的方式求解,对每个节点,求其左右子树的高度和左下叶子,如果高度相等,返回左子树的左下叶子,否则返回高度较高的子树的左下叶子。
public int findBottomLeftValue(TreeNode root) {
return find(root)[1];
}
public int[] find(TreeNode root){
int[] re = new int[2];
if(root == null){
re[0] = 0;
re[1] = 0;
return re;
}
if(root.left == null && root.right == null){
re[0] = 1;
re[1] = root.val;
return re;
}
int[] reLeft = find(root.left);
int[] reRight = find(root.right);
if(reLeft[0] >= reRight[0]){
re[0] = reLeft[0] + 1;
re[1] = reLeft[1];
}
else{
re[0] = reRight[0] + 1;
re[1] = reRight[1];
}
return re;
}