513.找二叉树左下角的值
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
//中结点一定不是深度最大的→前中后序没区别;
//深度最大左结点都是第一个遍历的:左中右,左右中,中左右
void pre_order(struct TreeNode* root, int depth, int* result, int* max_depth) {
if (root) {
//最下面一层最左结点;不一定是左孩子
//只有孩子结点才用操作
if (!root->left && !root->right) {
if (depth > (*max_depth)) {
//不能用=,不然在最下层会一直更新result
*result = root->val;
*max_depth = depth;
// printf("result=%d \n",*result);
}
}
pre_order(root->left, depth + 1, result, max_depth);
//包含了depth的回溯过程:depth++,--
//此处不用再&,因为result已经是指针,区别find里的result
pre_order(root->right, depth + 1, result, max_depth);
}
}
int findBottomLeftValue(struct TreeNode* root) {
int max_depth = INT_MIN;
int result = 0;
//不要用全局变量,会出问题
pre_order(root, 1, &result, &max_depth);
// printf("result=%d \n",result);
return result;
}
112. 路径总和
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool pre_order(struct TreeNode* root, int targetSum, int count) {
if (root) {
//在叶子结点判断
if (!root->left && !root->right && count == 0)
return true;
if (!root->left && !root->right && count != 0)
return false;
if (root->left) {//传参时对root->left 进行了解引用,所以要先判断是否为空指针
//传入参数之前先更新count(包含了回溯count)
if (pre_order(root->left, targetSum, count - root->left->val))
return true;
}
if (root->right) {
if (pre_order(root->right, targetSum, count - root->right->val))
return true;
}
}
return false;
}
bool hasPathSum(struct TreeNode* root, int targetSum) {
if (root) {
//传入参数之前先更新count
return pre_order(root, targetSum, targetSum - root->val);
}
return false;
}
106.从中序与后序遍历序列构造二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
//区间左闭右闭/左闭右开保持一致
//先切中序再切后序
//用数组大小来切后序
struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize) {
if(inorderSize==0) return NULL;
struct TreeNode* node=(struct TreeNode*)calloc(1,sizeof(struct TreeNode));
node->val=postorder[postorderSize-1];
//printf("in_size=%d,po_size=%d\n",inorderSize,postorderSize);
//printf("node->val=%d\n",node->val);
if(inorderSize==1) return node;
int inorder_left_index=0;
for(;inorder_left_index<inorderSize;inorder_left_index++){
if(inorder[inorder_left_index]==node->val) break;
}
//printf("inorder_left_index=%d\n",inorder_left_index);
node->left=buildTree(inorder,inorder_left_index,postorder,inorder_left_index);
// printf("4\n");
node->right=buildTree(inorder+inorder_left_index+1,inorderSize-1- inorder_left_index,postorder+inorder_left_index,inorderSize-1-inorder_left_index);
//printf("5\n");
return node;
}