Leetcode:513. Find Bottom Left Tree Value

来源:互联网 发布:windows怎么更新系统 编辑:程序博客网 时间:2024/06/11 07:14

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.

注意:!!!
是求 最后一层最左边的元素的val

//Definition for a binary tree node.    public class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int x) { val = x; }    }    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) {            //初始化的时候h=0 此时为根结点 h为1            if (h<depth) {ans=root.val;h=depth;}            /**             * 递归 直到Find The Ans             */            //如果root的左孩子不为空 递归 根结点变为左孩子 深度加1            if (root.left!=null) findBottomLeftValue(root.left, depth+1);            if (root.right!=null) findBottomLeftValue(root.right, depth+1);        }    }
原创粉丝点击