Advertisement
jibha

Untitled

Jan 31st, 2022
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14.  
  15. int maxdepth(TreeNode* root){
  16.  
  17. if(root==nullptr){
  18. return 0;
  19. }
  20.  
  21. return max(1+maxdepth(root->left),1+maxdepth(root->right));
  22.  
  23.  
  24. }
  25.  
  26. void dfs(TreeNode* root,vector<vector<string>>& ans,int i,int j,int depth){
  27.  
  28. if(root==nullptr){
  29. return;
  30. }
  31.  
  32.  
  33. depth--;
  34. ans[i][j]=to_string(root->val);
  35.  
  36. if(i+1<ans.size()){
  37. dfs(root->left,ans,i+1,j-depth-1,depth);
  38. dfs(root->right,ans,i+1,j+depth+1,depth);
  39. }
  40.  
  41. return;
  42.  
  43. }
  44.  
  45.  
  46. vector<vector<string>> printTree(TreeNode* root) {
  47.  
  48.  
  49. vector<vector<string>> ans;
  50.  
  51. int depth=maxdepth(root);
  52.  
  53. cout<<depth<<endl;
  54.  
  55.  
  56. for(int i=0;i<depth;i++){
  57.  
  58. vector<string> temp;
  59. for(int j=0;j<pow(2,depth)-1;j++){
  60. temp.push_back("");
  61. }
  62. ans.push_back(temp);
  63. }
  64.  
  65. dfs(root,ans,0,depth+depth%2-1,depth-1);
  66.  
  67. return ans;
  68. }
  69. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement