给一棵二叉树 {3,9,20,#,#,15,7} :
3
/ \
9 20
. . / \
..15 7
返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
]
class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public:
vector<vector<int>> levelOrder(TreeNode *root) {
// write your code here
vector<vector<int> >res;
if (root == NULL) {
return res;
}
queue<TreeNode* >q; //申请队列
q.push(root);
while(!q.empty()){
int size = q.size();//每次循环size次
vector<int> level;
for (int i = 0; i< size; i++){
TreeNode* top = q.front();
q.pop();
level.push_back(top->val);
if(top->left != NULL) q.push(top->left);
if(top->right != NULL) q.push(top->right);
}
res.push_back(level);
}
return res;
}
};
给一棵二叉树,找出从根节点到叶子节点的所有路径。
1
/ \
2 3
\
5
所有根到叶子的路径为:
[
“1->2->5”,
“1->3”
]
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
void helper(TreeNode* root, string str, vector<string>& res){
if (root == NULL) {
return ;
}
else if (root != NULL && root->left == NULL && root->right == NULL){
str += to_string(root->val);
res.push_back(str);
return ;
}
str += to_string(root->val);
if (root->left != NULL){
string temp = str + "->";
helper(root->left, temp, res);
}
if (root->right != NULL){
string temp = str + "->";
helper(root->right, temp, res);
}
return ;
}
vector<string> binaryTreePaths(TreeNode* root) {
// Write your code here
string str;
vector<string> res;
helper(root, str, res);
return res;
}
};
给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
1
/ \
2 3
return 6
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int ans = INT_MIN;
int maxPathSum(TreeNode *root) {
maxPath(root);
return ans;
}
int maxPath(TreeNode* root){
if (root == NULL) return 0;
int left = 0,right = 0;
if (root ->left) left = maxPath(root ->left);
if (root ->right) right = maxPath(root ->right);
int sum = root ->val + max(0, left) + max(0, right);
ans = max (ans, sum);
return root ->val + max(0, max(left, right));
}
};