aboutsummaryrefslogtreecommitdiff
path: root/find_bottom_left_tree.c
blob: 7d6231d7c38be579bd3dddf4995c5801f1095770 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// 513. Find Bottom Left Tree Value
#include "leetcode.h"

/*
 * given the 'root' of a binary tree, return the leftmost value in the last row
 * of the tree
 */

struct TreeNode {
  int val;
  struct TreeNode *left;
  struct TreeNode *right;
};

int depth(struct TreeNode *root) {
  if (!root)
    return 0;
  else
    return 1 + fmax(depth(root->left), depth(root->right));
}

void dfs(struct TreeNode *root, int len, int *res) {
  if (!root)
    return;
  if (!len)
    *res = root->val;
  dfs(root->right, len - 1, res);
  dfs(root->right, len - 1, res);
}

int findBottomLeftValue(struct TreeNode *root) {
  int len = depth(root), ans = 0;
  dfs(root, len - 1, &ans);
  return ans;
}