把二叉树打印成多行

你快乐吗?

Posted by bbkgl on October 17, 2019

对一张琴

一壶酒

一溪云

C++,层序遍历,和上题几乎一样的。

思路直接看上一道题吧。

非递归:

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
        vector<vector<int> > Print(TreeNode* pRoot) {
            vector<vector<int>> ans;
            if (!pRoot) return ans;
            queue<TreeNode *> q;
            q.push(pRoot);
            while (!q.empty()) {
                vector<int> tempv;
                int cnt = q.size();
                while (cnt) {
                    TreeNode *cur = q.front();
                    q.pop();
                    tempv.push_back(cur->val);
                    if (cur->left)
                        q.push(cur->left);
                    if (cur->right)
                        q.push(cur->right);
                    cnt--;
                }
                ans.push_back(tempv);
            }
            return ans;
        }
    
};

递归:

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
        vector<vector<int> > Print(TreeNode* pRoot) {
            vector<vector<int>> ans;
            dfs(pRoot, ans, 0);
            return ans;
        }
    
        void dfs(TreeNode *root, vector<vector<int>> &ans, int depth) {
            if (!root) return ;
            if (depth >= ans.size())
                ans.push_back(vector<int> {});
            ans[depth].push_back(root->val);
            dfs(root->left, ans, depth + 1);
            dfs(root->right, ans, depth + 1);
        }
};