二叉树的递归1

来源:互联网 发布:淘宝申请退款卖家拒绝 编辑:程序博客网 时间:2024/05/16 01:22

题目1:Binary Tree Maximum Path Sum
题目要求:
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
就是求出值最大的路径。

这个题很难。最开始我做的时候,没有充分考虑到负数存在的情况。 这个题类似于求最大子数组的问题。但他是两个方向的。 递归的关键:在于把一个方向上(和较大的方向)的递归到上一级,同时比较下每一个子树的最大值。注意传递和比较的不相同。传递的单方向的,而比较的是两个方向上的。
代码如下:
/**
* 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:    int maxPathSum(TreeNode* root) {        int max=INT_MIN;        dfs(root,max);        return max;    }private:    int dfs(TreeNode* root, int& maxsum){        if(root==NULL) return 0;        int sum=root->val;        int left=dfs(root->left,maxsum);        int right=dfs(root->right,maxsum);        if(left>0) sum+=left;        if(right>0) sum+=right;        maxsum=max(maxsum,sum);        return max(left,right)>0 ? max(left,right)+root->val:root->val;    }};

代码解释:dfs函数是关键所在。maxsum这一变量采用引用传值,相当于定义了一个全局变量。把maxsum定义为全局变量也是OK的。

这段代码的// 时间复杂度 O(n) ,空间复杂度 O(logn)
关于递归的时间复杂度详见我收藏的一篇文章。
空间复杂度我认为是O(logN),是大O记法,底数为2。

注: stray ‘\357’ in program这个编译错误是指把汉语字符引入了(括号或者分号等)

题目2:Binary Tree Right Side View
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
就是从右边看二叉树,返回一个vector
采用递归和迭代两种方式。
迭代使用一个栈,关键是记录每个节点所在的层数。

class Solution {public:    vector<int> rightSideView(TreeNode* root) {        vector<int> view;        if(rand()%2){            rightSideViewhelper(root,view);        }else{            rightSideViewhelper(root,1,view);        }        return view;    }private:    void rightSideViewhelper(TreeNode* root,int level, vector<int>& view){//level不能定义为引用哦。因为不想把他当成一个全局变量。因为回溯的时候我希望用他上一层的值哦。        if(root==NULL) return;        if(view.size()<level) view.push_back(root->val);        rightSideViewhelper(root->right,level+1,view);        rightSideViewhelper(root->left,level+1,view);    }    void rightSideViewhelper(TreeNode* root,vector<int>& view){        if(root==NULL) return;//少了这个会报错runtime error        vector<TreeNode*> stack;        vector<int> level;**记录每个节点对应的所在的层数**       stack.push_back(root);        level.push_back(1);        while(stack.size()>0){            TreeNode* p=stack.back();            stack.pop_back();            int l=level.back();            level.pop_back();            if(view.size()<l)  view.push_back(p->val);            if(p->left){                stack.push_back(p->left);                level.push_back(l+1);            }            if(p->right){                stack.push_back(p->right);                level.push_back(l+1);            }          }     }};
0 0