IncredibleThings

导航

LeetCode - Find Bottom Left Tree Value

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

 

Example 1:


Input: root = [2,1,3]
Output: 1
Example 2:


Input: root = [1,2,3,4,null,5,6,null,null,7]
Output: 7
 

Constraints:

The number of nodes in the tree is in the range [1, 104].
-231 <= Node.val <= 231 - 1

 

BFS:

/**
 * 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) {
        if (root == null) {
            return -1;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int res = root.val;
        while (!queue.isEmpty()){
            TreeNode node = queue.poll();
            if(node.right != null) {
                res = node.right.val;
                queue.add(node.right);
            }
            if (node.left != null) {
                res = node.left.val;
                queue.add(node.left);
            }
        }
        return res;
        
    }
}

 

DFS:

/**
 * 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 {
    int bottomLeft = 0;
    int maxDepth = -1;
    public int findBottomLeftValue(TreeNode root) {
        helper(root, -1);
        return bottomLeft;
    }
    private void helper (TreeNode node, int depthOfParent) {
        if (node == null) {
            return;
        }
        int curDepth = depthOfParent + 1;
        
        if (curDepth > maxDepth) {
            bottomLeft = node.val;
            maxDepth = curDepth;
        }
        
        helper(node.left, curDepth);
        helper(node.right, curDepth);
    }
}

 

posted on 2021-02-09 13:37  IncredibleThings  阅读(66)  评论(0编辑  收藏  举报