[InterviewBit] Last Node in a Complete Binary Tree

Last Node in a Complete Binary Tree

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void dfs(TreeNode* A, int dep, pair<int,int>& res) {
if(!A) return;
if(res.first < dep) res = {dep,A->val};
else if(res.first == dep) res.second = A->val;
dfs(A->left, dep + 1, res);
dfs(A->right, dep + 1, res);
}
int Solution::lastNode(TreeNode* A) {
pair<int, int> res{-1,-1};
dfs(A, 0, res);
return res.second;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/16/PS/interviewbit/last-node-in-a-complete-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.