leetcode思路总结反思(Tree篇)

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);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值