Day 16 二叉树
513. Find Bottom Left Tree Value
思路:
- 递归: 用中序遍历确保左节点最先visit,再记录最大深度
- BFS
// 递归
class Solution {
public:
int depth = INT_MIN;
int res = 0;
void traverse(TreeNode* root, int d) {
if (!root) {
return;
}
traverse(root->left, d + 1);
if (!root->left && !root->right) {
if (d > depth) {
res = root->val;
depth = d;
}
return;
}
traverse(root->right, d + 1);
}
int findBottomLeftValue(TreeNode* root) {
traverse(root, 0);
return res;
}
};
- 如果需要搜索整棵二叉树且不用处理递归返回值,递归函数就不要返回值。(113.路径总和ii)
- 如果需要搜索整棵二叉树且需要处理递归返回值,递归函数就需要返回值。 (236. 二叉树的最近公共祖先中介绍)
- 如果要搜索其中一条符合条件的路径,那么递归一定需要返回值,因为遇到符合条件的路径了就要及时返回。
106. Construct Binary Tree from Inorder and Postorder Traversal
class Solution {
public:
TreeNode* helper(int postend, int instart, int inend, vector<int>&in, vector<int>&post) {
if (postend < 0 || instart > inend) {
return NULL;
}
TreeNode* root = new TreeNode(post[postend]);
int idx = 0;
for (int i = instart; i <= inend; i++) {
if (in[i] == post[postend]) {
idx = i;
break;
}
}
root->left = helper(postend - (inend - idx + 1), instart, idx - 1, in, post);
root->right = helper(postend - 1, idx + 1, inend, in, post);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return helper(postorder.size() - 1, 0, inorder.size() - 1, inorder, postorder);
}
};
105. Construct Binary Tree from Preorder and Inorder Traversal
class Solution {
public:
TreeNode* helper(int prestart, int instart, int inend, vector<int>&pre, vector<int>&in) {
if (prestart >= pre.size() || instart > inend) {
return NULL;
}
TreeNode* root = new TreeNode(pre[prestart]);
int idx = 0;
for (int i = instart; i <= inend; i++) {
if (in[i] == pre[prestart]) {
idx = i;
break;
}
}
root->left = helper(prestart + 1, instart, idx - 1, pre, in);
root->right = helper(prestart + idx - instart + 1, idx + 1, inend, pre, in);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return helper(0, 0, inorder.size() - 1, preorder, inorder);
}
};
前序和后序不能唯一确定一棵二叉树,因为没有中序遍历无法确定左右部分,无法分割。