Topic description
Print the binary tree layer by layer from top to bottom, and the nodes in the same layer are output from left to right. Each layer outputs one line.
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; */ //loop solution class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int>> v; if(pRoot == NULL) return v; queue<TreeNode *> qu; TreeNode * p = NULL; qu.push(pRoot); vector<int> t;int count = 0; while(!qu.empty()){ count = qu.size();//Get the number of nodes in each layer while(count--){ p = qu.front(); t.push_back(p->val); if(p->left) qu.push(p->left); if(p->right) qu.push(p->right); qu.pop(); } v.push_back(t); t.clear(); } return v; } }; //Recursive writing, depth-first traversal. Use the depth of the stack and the height of the tree to compare class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int>> v; if(pRoot == NULL) return v; dfs(pRoot,1,v); return v; } void dfs(TreeNode* root,int depth,vector<vector<int>> &v) { if(root == NULL)return ; if(depth > v.size()) v.push_back(vector<int>()); v[depth - 1].push_back(root->val); dfs(root->left,depth + 1, v); dfs(root->right,depth + 1, v); } };