《LeetCode力扣练习》代码随想录——二叉树(找树左下角的值—Java)
刷题思路来源于 代码随想录
513. 找树左下角的值
-
二叉树
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int result; private int maxDepth = Integer.MIN_VALUE; public int findBottomLeftValue(TreeNode root) { recursion(root, 1); return result; } private void recursion(TreeNode root, int depth) { if (root.left == null && root.right == null) { if (depth > maxDepth) { maxDepth = depth; result = root.val; } } if (root.left != null) { depth++; recursion(root.left, depth); depth--; } if (root.right != null) { depth++; recursion(root.right, depth); depth--; } } }