Leetcode513. 找树左下角的值(C语言)
数据结构-树:算法与数据结构参考
题目:
给定一个二叉树,在树的最后一行找到最左边的值。
输入:[1,2,3,4,null,5,6,null,null,7]
输出:7
思路:
先序遍历(根,左,右),每次/层 存储最左节点值
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int depth(struct TreeNode* root){ // 计算深度
if(root == NULL) return 0;
int l = depth(root->left);
int r = depth(root->right);
return 1 + (l > r ? l : r);
}
void preOrder(struct TreeNode* root,int h,int curH,int* m){
if(root == NULL) return ;
if(curH == h){ //当前深度=总深度
*m = root->val;
return ;
}
preOrder(root->right,h,curH+1,m); //由于求最左的值,顺序不能倒
preOrder(root->left,h,curH+1,m); //否则本例输出为6
}
int findBottomLeftValue(struct TreeNode* root) {
int h = depth(root); //深度
int m = root->val; //左下角的值
int curh=1; //当前深度
preOrder(root,h,curh,&m);
return m;
}