513. 找树左下角的值

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public int findBottomLeftValue(TreeNode root) {
  18. Queue<TreeNode> q = new LinkedList<>();
  19. q.offer(root);
  20. TreeNode ans = root;
  21. while (!q.isEmpty()){
  22. int size = q.size();
  23. ans = q.peek();
  24. for (int i = 0; i < size; i++) {
  25. TreeNode poll = q.poll();
  26. if (poll.left != null) q.offer(poll.left);
  27. if (poll.right != null) q.offer(poll.right);
  28. }
  29. }
  30. return ans.val;
  31. }
  32. }

点我递归
如果需要遍历整棵树,递归函数就不能有返回值。如果需要遍历某一条固定路线,递归函数就一定要有返回值!
本题我们是要遍历整个树找到最深的叶子节点,需要遍历整棵树,所以递归函数没有返回值

// 递归法
class Solution {
    private int Deep = -1;
    private int value = 0;
    public int findBottomLeftValue(TreeNode root) {
        value = root.val;
        findLeftValue(root,0);
        return value;
    }

    private void findLeftValue (TreeNode root,int deep) {
        if (root == null) return;
        if (root.left == null && root.right == null) {
            if (deep > Deep) {
                value = root.val;
                Deep = deep;
            }
        }
        if (root.left != null) findLeftValue(root.left,deep + 1);
        if (root.right != null) findLeftValue(root.right,deep + 1);
    }
}