剑指 Offer II 045. 二叉树最底层最左边的值(513. 找树左下角的值)

题目:

 

 

 

思路:

【1】递归的方式

【2】循环的方式

代码展示:

递归的方式:

//时间0 ms击败100%
//内存41.1 MB击败41.2%
//时间复杂度:O(n),其中 n 是二叉树的节点数目。需要遍历 n 个节点。
//空间复杂度:O(n)。递归栈需要占用 O(n) 的空间。
class Solution {
    int curVal = 0; //当前值
    int curHeight = 0; //当前高度
    public int findBottomLeftValue(TreeNode root) {
        curHeight = 0;
        dfs(root, curHeight);
        return curVal;
    }
    void dfs(TreeNode root, int height){
        if(root == null) return;
        height ++;
        dfs(root.left, height);
        dfs(root.right, height);
        if(height > curHeight){
            curHeight = height;
            curVal = root.val;
        }
    }
}

 

循环的方式:

//时间1 ms击败70.16%
//内存41.3 MB击败12.84%
//时间复杂度:O(n),其中 n 是二叉树的节点数目。
//空间复杂度:O(n)。如果二叉树是满完全二叉树,那么队列最多保存 n/2 个节点。
/**
 * 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) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        TreeNode temp;
        int res = 0;
        while (!queue.isEmpty()){
            int size = queue.size();
            int flag = 1;
            while (size-- > 0){
                temp = queue.poll();
                if (flag-- == 1) res = temp.val;
                if (temp.left != null) queue.add(temp.left);
                if (temp.right != null) queue.add(temp.right);
            }
        }
        return res;
    }
}

//当然如果省略标志位的话
class Solution {
    public int findBottomLeftValue(TreeNode root) {
        int ret = 0;
        Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode p = queue.poll();
            if (p.right != null) {
                queue.offer(p.right);
            }
            if (p.left != null) {
                queue.offer(p.left);
            }
            ret = p.val;
        }
        return ret;
    }
}

 

posted @ 2023-03-21 12:19  忧愁的chafry  阅读(14)  评论(0)    收藏  举报