Eg : Find bottom left node value in a tree.
Here, I am using two global variables :
public int maxLevel = 0;
public TreeNode nodeLeft;
Is it a good practice?
https://leetcode.com/problems/find-bottom-left-tree-value/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxLevel = 0;
public TreeNode nodeLeft;
public int findBottomLeftValue(TreeNode root) {
if(root == null)
return 0;
nodeLeft = root;
helper(root, 0);
return nodeLeft.val;
}
public void helper(TreeNode root, int depth){
if(root==null)
return;
if(root.left == null && root.right == null && maxLevel<depth){
maxLevel = depth;
nodeLeft = root;
return;
}
helper(root.left, depth+1);
helper(root.right, depth+1);
}
}