Leetcode 513 找树的最左下角叶子
使用迭代的层序遍历方法会更简单一些。
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> que;
int result;
que.push(root);
while(!que.empty()){
int _size = que.size();
for(int i = 0; i < _size; i++){
TreeNode* node = que.front();
que.pop();
if(i == 0) {result = node -> val;}
if(node -> left != NULL) {que.push(node -> left);}
if(node -> right != NULL) {que.push(node -> right);}
}
}
return result;
}
};
Leetcode 112 路径求和
和找所有路径类似。
class Solution {
public:
bool isTarget(TreeNode* node, vector<int> &path, int targetSum){
path.push_back(node -> val);
if(node -> left == NULL && node -> right == NULL){
int sum = 0;
for(int i = 0; i < path.size(); i++){
sum += path[i];
}
if(targetSum == sum) {return true;}
else{return false;}
}
bool leftTarget = false, rightTarget = false;
if(node -> left){
leftTarget = isTarget(node -> left, path, targetSum);
path.pop_back();
}
if(node -> right){
rightTarget = isTarget(node -> right, path, targetSum);
path.pop_back();
}
return leftTarget || rightTarget;
}
bool hasPathSum(TreeNode* root, int targetSum) {
vector<int> path;
if(root == NULL) {return false;}
return isTarget(root, path, targetSum);
}
};
Leetcode 106 中序后序构造二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* traversal(vector<int> &inorder, vector<int> &postorder){
if(postorder.size() == 0) {return NULL;}
int rootValue = postorder[postorder.size() - 1];
TreeNode* root = new TreeNode(rootValue);
//在中序数组找到分割点
if(postorder.size() == 1) {return root;}
int index;
for(index = 0; index < inorder.size(); index++){
if(inorder[index] == rootValue) {break;}
}
postorder.resize(postorder.size() - 1);
//切割中序数组
vector<int> inorderLeft(inorder.begin(), inorder.begin() + index);
vector<int> inorderRight(inorder.begin() + index + 1, inorder.end());
//切割后序数组
vector<int> postorderLeft(postorder.begin(), postorder.begin() + inorderLeft.size());
vector<int> postorderRight(postorder.begin() + inorderLeft.size(), postorder.end());
root -> left = traversal(inorderLeft, postorderLeft);
root -> right =traversal(inorderRight, postorderRight);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if(inorder.size() == 0 || postorder.size() == 0) {return NULL;}
return traversal(inorder, postorder);
}
};