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

513. Find Bottom Left Tree Value

时间:2017-08-06 19:39:27      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:row   先序遍历   mos   tle   and   tput   view   ast   for   

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.

现在开始考bfs 了吗, 根据size办事,分情况了

public int findBottomLeftValue(TreeNode root) {
        if (root == null) return -1;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        int ans = 1;
        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = q.poll();
                    
                    if (cur.left != null) {
                        q.offer(cur.left);
                    }
                    if (cur.right != null) {
                        q.offer(cur.right);
                    }
                if (i == 0) {
                    ans = cur.val;
                }
            }
        }
        return ans;
    }

dfs: 先序遍历  + 树的深度, 跟此题类似: 199 Binary Tree Right Side View

public class Solution {
    int deep = 0;
    int ans = -1;
    public int findBottomLeftValue(TreeNode root) {
        if (root == null) return -1;
        //int curDeep = 0;
        dfs(root, 0);
        return ans;
    }
    private void dfs(TreeNode root, int curDeep) {
        if (root == null)  {
            return;
        }
        if (root.left ==  null && root.right == null && deep == curDeep) {
            deep++;
            ans = root.val;
            return;
        }
        if (deep == curDeep) {
            deep++;
            //curDeep++;
        }
        dfs(root.left, curDeep + 1);
        dfs(root.right, curDeep + 1);
            
    }
}

  

 

513. Find Bottom Left Tree Value

标签:row   先序遍历   mos   tle   and   tput   view   ast   for   

原文地址:http://www.cnblogs.com/apanda009/p/7295517.html

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