leetcode思路总结反思(Tree篇)
模板:树的各种遍历方式:
(1)中序遍历
递归:
void Inorder(TreeNode* root,vector<int>& res)
{
if(root==NULL)
return;
Inorder(root->left,res);
res.push_back(root->val);
Inorder(root->right,res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
Inorder(root,res);
return res;
}
非递归:
(2)先序遍历
递归:
void Preorder(TreeNode* root,vector<int>& res)
{
if(root==NULL)
return;
res.push_back(root->val);
Preorder(root->left,res);
Preorder(root->right,res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
Preorder(root,res);
return res;
}
非递归:
(3)后序遍历
递归:
void Postorder(TreeNode* root,vector<int>& res)
{
if(root==NULL)
return;
Postorder(root->left,res);
Postorder(root->right,res);
res.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
Postorder(root,res);
return res;
}
非递归:
(4)之字型遍历
(5)先序遍历变形:
很多题都可以套用这个模板的做法!!!ex:
515. Find Largest Value in Each Tree Row
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> res;
ctx(res,0,root);
return res;
}
void ctx(vector<int> & res,int depth,TreeNode * root)
{
if(root==NULL)
return;
if(depth==res.size())
res.push_back(root->val);
else
res[depth]=max(res[depth],root->val);
ctx(res,depth+1,root->right);
ctx(res,depth+1,root->left);
}
};