Commit 3e4e27dd authored by yaozc's avatar yaozc
Browse files

Tuesday night. Keep going!!!

parent d00e3a5a
......@@ -470,13 +470,98 @@ public:
}
res.push_back(temp);
}
return res;
}
};
Binary Tree Zigzag Level Order Traversal
//和上一题BFS不同的是,zigzag使用的是2个stack,奇数层用s1,偶数层用s2。
// 奇数层先看left sub tree,然后right sub tree. 偶数层先看right sub tree, 然后left sub tree
// https://www.youtube.com/watch?v=YsLko6sSKh8&t=49s
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
stack<TreeNode*> s1;
stack<TreeNode*> s2;
s1.push(root);
int level = 0;
while( !s1.empty()|| !s2.empty()) {
if(level%2 == 0){
vector<int> temp;
while(!s1.empty()){
cout<<"1"<<endl;
TreeNode* curr = s1.top();
s1.pop();
temp.push_back(curr->val);
if(curr->left) s2.push(curr->left);
if(curr->right) s2.push(curr->right);
}
res.push_back(temp);
}
else{
vector<int> temp;
while(!s2.empty()){
cout<<"2"<<endl;
TreeNode* curr = s2.top();
s2.pop();
temp.push_back(curr->val);
if(curr->right) s1.push(curr->right);
if(curr->left) s1.push(curr->left);
}
res.push_back(temp);
}
level++;
cout<<"3"<<endl;
}
return res;
}
};
Binary Tree Maximum Path Sum
// not fully understood
// 大体意思为,因为可以不包含root,所以随时要考虑是否应该用 new_path,来代替包含root的old path
// 要随时和0比较是因为有可能出现左右分支都小于0的情况 (避免sum有可能被加上了较小的那个负数情况)
// return的内容是为recursion服务的,传回的值为parent加上一个较大的noded情况
class Solution {
int sum = INT_MIN;
public:
int maxPathSum(TreeNode* root) {
max_gain(root);
return sum;
}
int max_gain(TreeNode* parent){
if(!parent) return 0;
int left = max(max_gain(parent->left), 0);
int right = max(max_gain(parent->right), 0);
int new_path = left + right + parent->val;
sum = max(sum, new_path);
return max(parent->val + max(left, right), 0);
}
};
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment