how to make a function from using global var to not using it
let say, we want to find the bottom left node in a tree.
one way to do it is using global vars:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int findBottomLeftValue(TreeNode root) { find(root, 0); return d_bottomLeft.val; } private int d_bottomDepth = -1; private TreeNode d_bottomLeft = null; private void find(TreeNode node, int depth) { if (node == null) return; if (depth >= d_bottomDepth) { d_bottomDepth = depth; d_bottomLeft = node; } find(node.right, depth + 1); find(node.left , depth + 1); } }
to avoid using global vars, we can write it in this way:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int findBottomLeftValue(TreeNode root) { Result result = new Result(); find(root, 0, result); return result.d_bottomLeft.val; } private void find(TreeNode node, int depth, Result result) { if (node == null) return; if (depth >= result.d_bottomDepth) { result.d_bottomDepth = depth; result.d_bottomLeft = node; } find(node.right, depth + 1, result); find(node.left , depth + 1, result); } private class Result { public int d_bottomDepth = -1; public TreeNode d_bottomLeft = null; } }