513. Find Bottom Left Tree Value

来源:互联网 发布:985软件工程硕士工资 编辑:程序博客网 时间:2024/06/08 16:59

1.题目
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
Note: You may assume the tree (i.e., the given root node) is not NULL.

2.分析
这是一道树形结构的题目,寻找左子树做后一层最左边的位置,很明显的采用递归的方法。
3.解题
我的解法

class Solution {public int findBottomLeftValue(TreeNode root) {    // 这道题假设树非空    int result = 0; // 最终的返回值    int depth = findDepth(root);    if(depth==1){        return root.val;    }    if(root==null){        return 0;    }    int left = findDepth(root.left);    int right = findDepth(root.right);    if(left>=right){        result = findBottomLeftValue(root.left); // 递归左子树    }else{        result = findBottomLeftValue(root.right); // 递归右子树    }    return result;}// 查找树的层数public int findDepth(TreeNode node){    if(node==null){        return 0;    }    if(node!=null&&node.left==null&&node.right==null){        return 1;    }    return Math.max(1+findDepth(node.left),1+findDepth(node.right));}}

4.总结
看了一下其他人的解法其实也是大同小异,就是递归调用中,因为寻找的是最后一层最左边的树节点,所以首先会判断,树的深度,然后比较去递归左子树或右子树,寻找它的最左数值,即为最后的结果。

原创粉丝点击