LeetCode-Find Bottom Left Tree Value

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83511230

一、Description

Given a binary tree, find the leftmost value in the last row of the tree.

题目大意:

给出一个二叉树,找出最后一行最左边的结点值。

Example 1:

Input:

    2
   / \
  1   3

Output:
1

Example 2: 

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7

二、Analyzation

这里提供两种思路:

1.先求出二叉树的高度,然后通过层次遍历,等到遍历到最后一行时,直接返回此时队列中的第一个结点即为所求,见代码一。

2.在递归函数的参数列表中加入一个level,在递归遍历的同时level加一,如果在同一层,那么首先递归返回的一定是该层最左边的结点(根据递归顺序),因此最后的left即为所求。


三、Accepted code

代码一:

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        int h = height(root);
        int val = 0, size = 0;
        queue.add(root);
        while (!queue.isEmpty()) {
           h--;
            if (h == 0) {
                val = queue.poll().val;
                break;
            }
            size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                size--;
            }
        }
        return val;
    }
    public int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        int leftHeight = 0, rightHeight = 0;
        if (root.left != null) {
            leftHeight = height(root.left) + 1;
        }
        if (root.right != null) {
            rightHeight = height(root.right) + 1;
        }
        return leftHeight > rightHeight ? leftHeight : rightHeight;
    }
}

代码二:

class Solution {
    int left = 0;
    int preLevel = 0;
    
    public int findBottomLeftValue(TreeNode root) {
        left = root.val;
        help(root, 0);
        return left;
    }
    
    public void help(TreeNode root, int level) {
        if(root.left != null) {
            help(root.left, level + 1);
        }
        if(root.right != null) {
            help(root.right, level + 1);
        }
        if(level > preLevel) {
            left = root.val;
            preLevel = level;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Apple_hzc/article/details/83511230