找树左下角的值 (Find Bottom Left Tree Value)

 

思路:

// @Title: 找树左下角的值 (Find Bottom Left Tree Value)
// @Author: qisiii
// @Date: 2024-09-15 17:03:05
// @Runtime: 3 ms
// @Memory: 43.5 MB
// @comment: 
// @flag: 
/**
 * 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;
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            boolean flag=true;
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if(flag){
                    result=node.val;
                    flag=false;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
        }
        return result;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18