leetcode513_找到左下角的值

这道题的递归比迭代要难写,recursion是一道树上带回溯,iteration几乎套层次遍历即可。

1.递归写法

说白了就是要找到深度最大的叶子节点
?如何保证深度最大的就是最左的?——使用前序遍历
?为什么使用的是前序遍历而不是更倾向于左边的中序遍历
前序遍历中最先访问到的就是最左边的叶子节点。
我们对每个结点的操作是:如果他是叶子节点,则更新深度,否则就继续往下走。

class Solution {
    private int maxDeep = -1;
    private int maxLeftValue = 0;
    public int findBottomLeftValue(TreeNode root) {
        traversal(root, 0);
        return maxLeftValue;
    }
    private void traversal(TreeNode root, int depth) {
        if(root.left == null && root.right == null) {
            if(depth > maxDeep) {
                maxDeep = depth;
                maxLeftValue = root.val;
            }
        }
        if(root.left != null) traversal(root.left, depth+1);
        if(root.right != null) traversal(root.right, depth+1);
    }
}

2.层次遍历写法

用一个值来表示每一层最左边的值即可,遍历结束该值保存的就是最后一层最左边的值,即题目所求

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        if(root == null) return 0;
        Queue<TreeNode> q = new LinkedList();
        q.offer(root);
        int ans = 0;
        while(!q.isEmpty()) {
            int size = q.size();
            for(int i = 0; i < size; i++) {
                TreeNode node =  q.poll();
                if(i == 0) ans = node.val;
                if(node.left != null) q.offer(node.left);
                if(node.right != null) q.offer(node.right);
            }
        }
        return ans;
    }
}
posted @ 2022-03-06 11:30  明卿册  阅读(26)  评论(0编辑  收藏  举报