码迷,mamicode.com
首页 > 其他好文 > 详细

513. Find Bottom Left Tree Value

时间:2020-01-23 11:15:55      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:root   otto   nod   朋友   put   most   integer   size   inpu   

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.

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        List<List<Integer>> help = levelOrder(root);
        return help.get(help.size() - 1).get(0);
    }
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Helper(0, root, res);
        return res;
    }
    public void Helper(int height, TreeNode p, List<List<Integer>> res){
        if(p == null) return;
        if(height == res.size()){
            res.add(new ArrayList());
        }
        res.get(height).add(p.val);
        Helper(height + 1, p.left, res);
        Helper(height + 1, p.right, res);
    }
}

首先是我们的老朋友level order

public class Solution {
    int ans=0, h=0;
    public int findBottomLeftValue(TreeNode root) {
        findBottomLeftValue(root, 1);
        return ans;
    }
    public void findBottomLeftValue(TreeNode root, int depth) {
        if (h<depth) {ans=root.val;h=depth;}
        if (root.left!=null) findBottomLeftValue(root.left, depth+1);
        if (root.right!=null) findBottomLeftValue(root.right, depth+1);
    }
}

513. Find Bottom Left Tree Value

标签:root   otto   nod   朋友   put   most   integer   size   inpu   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12230207.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!