public class FindBottomLeftValue {
public int findBottomLeftValue(TreeNode root){
Deque<TreeNode> deque = new LinkedList<>();
//记录最左叶子节点
int res =0;
deque.add(root);
while(!deque.isEmpty()){
int size = deque.size();for(int i =0;i<size;i++){
TreeNode node = deque.poll();if(i ==0){
res = node.val;}if(node.left != null) deque.offer(node.left);if(node.right != null) deque.offer(node.right);}}return res;}}
思路:
1.利用层序遍历
2.每次记录着一层的第一个节点,也就是最左边的节点
3.当队列遍历为空时,此时记录的值也就是最左边的值
// 递归法
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);}}