leetcode513 FindBottomLeftTreeValue Java

来源:互联网 发布:js获取当前日期 函数 编辑:程序博客网 时间:2024/05/22 13:29

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

解法1

递归算法 很好理解

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

解法2

非递归 顺序遍历,用队列存储每一行的节点。循环结束,队列中的第一个即为结果。

public int findBottomLeftValue(TreeNode root) {    int result = 0;    Queue<TreeNode> queue = new LinkedList<>();    queue.offer(root);    while(! queue.isEmpty()) {        int size = queue.size();        for(int i=0; i<size; i++) {            TreeNode curr = queue.poll();            if(i == 0) result = curr.val;            if(curr.left != null) queue.offer(curr.left);            if(curr.right != null) queue.offer(curr.right);        }    }    return result;}
0 0
原创粉丝点击