您的位置:首页 > 其它

二叉树的层次遍历(BFS),二叉树的所有路径,二叉树的最大路径和(分治)

2017-04-11 17:04 447 查看
给一棵二叉树 {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));
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐