Advertisement
Guest User

Untitled

a guest
May 25th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left;
  6. * public TreeNode right;
  7. * public TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public IList<IList<string>> PrintTree(TreeNode root) {
  12. int d = FindDepth(root);
  13. return BuildTree(root, d);
  14. }
  15.  
  16. private IList<IList<string>> BuildTree(TreeNode current, int rD)
  17. {
  18. if (rD <= 0) return null;
  19.  
  20. IList<IList<string>> ret = new List<IList<string>>();
  21.  
  22. if (rD == 1)
  23. {
  24. var sL = new List<string>();
  25.  
  26. if (current == null)
  27. {
  28. sL.Add("");
  29. }
  30. else
  31. {
  32. sL.Add(current.val.ToString());
  33. }
  34.  
  35. ret.Add(sL);
  36. return ret;
  37. }
  38.  
  39.  
  40. IList<IList<string>> leftT = BuildTree(current?.left, rD - 1);
  41. IList<IList<string>> rightT = BuildTree(current?.right, rD - 1);
  42.  
  43.  
  44. var fL = new List<string>();
  45. for (int i = 0; i < leftT[0].Count(); i++)
  46. {
  47. fL.Add("");
  48. }
  49.  
  50. if (current == null)
  51. {
  52. fL.Add("");
  53. }
  54. else
  55. {
  56. fL.Add(current.val.ToString());
  57. }
  58.  
  59. for (int i = 0; i < leftT[0].Count(); i++)
  60. {
  61. fL.Add("");
  62. }
  63. ret.Add(fL);
  64. for (int i = 0; i < leftT.Count(); i++)
  65. {
  66. var newL = new List<string>(leftT[i]);
  67. newL.Add("");
  68. newL.AddRange(rightT[i]);
  69. ret.Add(newL);
  70. }
  71. return ret;
  72. }
  73.  
  74. private int FindDepth(TreeNode current)
  75. {
  76. if (current == null) return 0;
  77. return Math.Max(FindDepth(current.right), FindDepth(current.left)) + 1;
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement