【数据结构】树题谱

144. 二叉树的前序遍历

算法1:递归写法

/**
 * 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:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        dfs(res,root);
        return res;
    }

    void dfs(vector<int> &res,TreeNode* root)
    {
        if(!root) return;
        res.push_back(root->val);
        dfs(res,root->left);
        dfs(res,root->right);
    }
};

算法2:非递归遍历

/**
 * 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:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> S;

        while(root || !S.empty()) // 模板写法
        {
            while(root){
                res.push_back(root->val);
                S.push(root);
                root = root->left;
            }

            if(!S.empty())
            {
                root = S.top();
                S.pop();
                root = root->right;
            }
        }

        return res;
        
        
    }
};

94. 二叉树的中序遍历

算法1:递归写法

/**
 * 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:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        dfs(res,root);
        return res;
    }

    void dfs(vector<int> &res,TreeNode* root)
    {
        if(!root) return; // 记得递归返回
        if(root->left) dfs(res,root->left);
        res.push_back(root->val);
        if(root->right) dfs(res,root->right);
    }
};

算法2:非递归遍历

/**
 * 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:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> S;

        while(root || !S.empty())
        {
            while(root){
                S.push(root);
                root = root->left;
            }

            if(!S.empty())
            {
                root = S.top();
                S.pop();
                res.push_back(root->val);
                root = root->right;
            }
            
        }

        return res;
    }
};

145. 二叉树的后序遍历

算法1:递归写法

/**
 * 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:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        dfs(res,root);
        return res;
    }

    void dfs(vector<int> &res,TreeNode* root) // 各种遍历只是递归顺序不同
    {
        if(!root) return; // 记得递归返回
        if(root->left) dfs(res,root->left);
        if(root->right) dfs(res,root->right);
        res.push_back(root->val);
    }
};

算法2:非递归遍历

后序遍历的顺序是:左右中, 先序遍历的顺序是:中左右;
可以修改先序遍历为:中右左,再将其转置;即得到左右中,后序遍历。

/**
 * 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:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> S;

        while(root || !S.empty()) // 模板写法
        {
            while(root){
                res.push_back(root->val);
                S.push(root);
                root = root->right;
            }

            if(!S.empty())
            {
                root = S.top();
                S.pop();
                root = root->left;
            }
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

严格按照定义,第三次访问的时候输出

/**
 * 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:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(!root) return res;

        stack<TreeNode*> S;
        TreeNode* cur = root, *pre = NULL;
        while(cur || !S.empty())
        {
            while(cur){
                S.push(cur);
                cur  = cur->left;
            }

            cur = S.top();
            if(cur->right == NULL || cur->right == pre){
                res.push_back(cur->val);
                S.pop();
                pre = cur;
                cur = NULL;
            }else{
                cur = cur->right;
            }
        }

        return res;
    }
};

102. 二叉树的层序遍历

算法1:BFS
计算每一层有多少个元素

/**
 * 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:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(!root) return res; // 判空

        queue<TreeNode*> q;
        q.push(root);
        while(q.size())
        {
            int size = q.size(); // 统计每层有多少个结点
            vector<int> cur;
            for(int i=0;i<size;i++)
            {
                auto t = q.front();
                q.pop();
                cur.push_back(t->val);
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
            res.push_back(cur);
        }

        return res;
    }
};

通过塞NULL来分层

/**
 * 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:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(!root) return res;

        queue<TreeNode*> q;
        q.push(root);
        q.push(NULL); // 通过塞NULL 来分层
        vector<int> cur;
        while(q.size())
        {
            auto t = q.front();
            q.pop();
            if(t) 
            {
                cur.push_back(t->val);
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
            else
            {
                res.push_back(cur);
                cur.clear();
                if(q.size()) q.push(NULL); // 要判断有元素才加,不然死循环
            }
        }

        return res; // 记得返回
    }
};

算法2:DFS

本题使用 DFS 同样能做。由于题目要求每一层的节点都是从左到右遍历,因此递归时也要先递归左子树、再递归右子树。

DFS 做本题的主要问题是: DFS 不是按照层次遍历的。为了让递归的过程中同一层的节点放到同一个列表中,在递归时要记录每个节点的深度 level。递归到新节点要把该节点放入 level 对应列表的末尾。

当遍历到一个新的深度 level,而最终结果 res 中还没有创建 level 对应的列表时,应该在 res 中新建一个列表用来保存该 level 的所有节点。

/**
 * 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:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        dfs(res,root,0); // (res,结点,层数);
        return res;
    }

    void dfs(vector<vector<int>> &res,TreeNode* root,int level)
    {
        if(!root) return;
        if(level >= res.size()) res.push_back(vector<int>()); // 开辟空间
        res[level].push_back(root->val);
        dfs(res,root->left,level + 1);
        dfs(res,root->right,level + 1);
    }
};

107. 二叉树的层次遍历 II

将顺序的结果逆序即可

/**
 * 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:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
            vector<vector<int>> res;
            if(!root) return res; // 判空

            queue<TreeNode*> q;
            q.push(root);
            while(q.size())
            {
                int size = q.size(); // 统计每层有多少个结点
                vector<int> cur;
                for(int i=0;i<size;i++)
                {
                    auto t = q.front();
                    q.pop();
                    cur.push_back(t->val);
                    if(t->left) q.push(t->left);
                    if(t->right) q.push(t->right);
                }
                res.push_back(cur);
            }

            reverse(res.begin(),res.end());

            return res;
    }
};

589. N叉树的前序遍历

算法1:递归写法

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    vector<int> preorder(Node* root) {
        vector<int> res;
        dfs(res,root);
        return res;
    }

    void dfs(vector<int> &res,Node* root)
    {
        if(!root) return;
        res.push_back(root->val);
        for(auto c : root->children) dfs(res,c);
    }
};

算法2:迭代写法

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    vector<int> preorder(Node* root) {
        vector<int> res;
        if(!root) return res;
        stack<Node*> S;
        S.push(root);

        while(S.size())
        {
            auto t = S.top();
            S.pop();

            res.push_back(t->val);
            auto tlist = t->children;
            for(int i=tlist.size()-1;i>=0;i--) S.push(tlist[i]);
        }
        
        return res;
    }
};

590. N叉树的后序遍历

算法1:递归遍历

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    vector<int> postorder(Node* root) {
        vector<int> res;
        dfs(res,root);
        return res;
    }

    void dfs(vector<int> &res,Node* root)
    {
        if(!root) return;
        for(auto c : root->children) dfs(res,c);
        res.push_back(root->val);
    }
};

算法2:前序遍历加逆序

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    vector<int> postorder(Node* root) {
        vector<int> res;
        if(!root) return res; // 判空
        stack<Node*> S;
        S.push(root);

        while(S.size()) // 根右左,逆序就变成左右根。
        {               // 根右左,需要在栈中先压入左,弹栈才是右左
            auto t = S.top();
            S.pop();
            res.push_back(t->val);
            for(auto c : t->children) 
                if(c) // 判空
                    S.push(c);
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

429. N叉树的层序遍历

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        vector<vector<int>> res;
        if(!root) return res;

        queue<Node*> q;
        q.push(root);
        while(q.size())
        {
            int n = q.size();
            vector<int> cur;
            for(int i=0;i<n;i++)
            {
                auto t = q.front();
                q.pop();
                cur.push_back(t->val);
                for(auto c : t->children) q.push(c);
            }
            res.push_back(cur);
        }
        return res;

    }
};

103. 二叉树的锯齿形层次遍历

对输出改变:层数为奇数的数组逆序即可

/**
 * 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:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(!root) return res;

        queue<TreeNode*> q;
        q.push(root);
        while(q.size())
        {
            int n = q.size();
            vector<int> cur;
            for(int i=0;i<n;i++)
            {
                auto t = q.front();
                q.pop();
                cur.push_back(t->val);
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
                
            }
            res.push_back(cur);
        }

        for(int i=0;i<res.size();i++)
            if(i % 2) reverse(res[i].begin(), res[i].end());
        
        return res;
    }
};

637. 二叉树的层平均值

层序遍历

/**
 * 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:
    vector<double> averageOfLevels(TreeNode* root) {
        vector<double> res;
        if(!root) return res;

        queue<TreeNode*> q;
        q.push(root);
        while(q.size())
        {
            int n = q.size();
            double cur = 0;
            for(int i=0;i<n;i++)
            {
                auto t = q.front();
                q.pop();
                cur += t->val;
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
            
            res.push_back(cur / n);
        }

        return res;
    }
};

104. 二叉树的最大深度

/**
 * 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 maxDepth(TreeNode* root) {
        int HL,HR,MaxH;
        if(root)
        {
            HL = maxDepth(root->left);
            HR = maxDepth(root->right);
            MaxH = max(HL,HR);
            return MaxH + 1;
        }
        else return 0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值