int maxDepth = INT_MIN;
int bottomLeftValue;
void traversal(struct TreeNode* root, int depth) {
if (root == NULL) {
return;
}
// 如果当前节点是叶子节点,并且当前深度大于已知的最大深度
if (root->left == NULL && root->right == NULL && depth > maxDepth) {
maxDepth = depth;
bottomLeftValue = root->val;
}
// 递归遍历左子树和右子树
traversal(root->left, depth + 1);
traversal(root->right, depth + 1);
}
int findBottomLeftValue(struct TreeNode* root) {
// 初始化最大深度为负无穷
maxDepth = INT_MIN;
// 调用遍历函数
traversal(root, 1); // 根节点的深度为1
// 返回最底层最左边节点的值
return bottomLeftValue;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool hasPathSum(struct TreeNode* root, int targetSum) {
if(!root)
return false;
if(!root->left && !root->right && targetSum == root->val)
return true;
return hasPathSum(root->left, targetSum- root->val) || hasPathSum(root->right, targetSum- root->val);
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int lineshreach(int* arr, int arrsize, int key){
int i;
for(i = 0; i < arrsize; i++){
if(arr[i] == key)
return i;
}
return -1;
}
struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize) {
if(!inorderSize)
return NULL;
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = postorder[postorderSize - 1];
int index = lineshreach(inorder, inorderSize,postorder[postorderSize-1]);
int rightSize = inorderSize - index - 1;
node->left = buildTree(inorder, index, postorder, index);
node->right = buildTree(inorder + index + 1, rightSize, postorder + index, rightSize);
return node;
}
题目给了两个数组,一个是后序,一个是中序,
后续和中序数组的作用
——由于后序,所以说该数组的最后一个是父结点,然后再从中序中,找到左右子树,找到后,就不断分割数组;
递归逻辑是
——停止条件是当中序数组的长度为零的时候,
先在后序数组中将根结点找出,然后在中序数组中以根结点位置,左右分割两个数组,左为左子树,右为右子树。