今天上完数据结构课后留了三道力扣上的题目,我在今天完成了前两道题目。
今天上完课后去科技楼开会,开完会走的时候还碰上了王建民老师,还说我们晚上有点闲,要给我们找活干,我们可一点也不闲啊......
94题:二叉树的中序遍历
/** * 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: void dotree(TreeNode* root,vector<int>*vec){ if(root){ if(root->left){ dotree(root->left,vec); } vec->push_back(root->val); if(root->right){ dotree(root->right,vec); } } } vector<int> inorderTraversal(TreeNode* root) { vector<int>vec; dotree(root,&vec); return vec; } };
194题:二叉树的最近公共祖先
/** * 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: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(!root||root==p||root==q) return root; TreeNode* left=lowestCommonAncestor(root->left,p,q); TreeNode* right=lowestCommonAncestor(root->right,p,q); if(!left) return right; if(!right) return left; return root; } };
标签:11,right,TreeNode,val,vec,root,left From: https://www.cnblogs.com/jiajiayu/p/17811404.html