Leetcode513. Find Bottom Left Tree Value

Given a binary tree, find the leftmost value in the last row of the tree

Basic idea:

I use two global variables to store current level value and current qualified answer.
Here are my naive solution.

class Solution{
    private int max = 0;//to store the current max level val.
    private int res = 0;// to store the current qualified val.
    public int findBottomLeftValue(TreeNode root) {
          helper(root,1);
          return res;
     }  
 public void helper(TreeNode node, int level){
        if(node == null){//base case 
           return ;
        }
        if(max < level){
            max = level;
            res = node.val;//update the max level value and res.
        }
         if (node.left!=null) helper(node.left,level+1);
         if (node.right!=null) helper(node.right,level+1);//left and righe node are in the same level 
         //if I use "level++"here, then when it comes to the right node, the level value has been increased,
        // thus, the right node level value is more than the left one, which is incorrect.
    }
}
    原文作者:Stan95
    原文地址: https://www.jianshu.com/p/45a5d061c91a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞