贴下自己写的不用指针的代码,更加容易懂吧
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<TreeNode *> dfs(int start, int end) { 13 vector<TreeNode *> subtree; 14 if (start > end) { 15 subtree.push_back(NULL); 16 return subtree; 17 } 18 for (int i = start; i <= end; i++) { 19 vector<TreeNode *> left = dfs(start, i-1); 20 vector<TreeNode *> right = dfs(i+1, end); 21 for (int j = 0; j < left.size(); j++) { 22 for (int k = 0; k < right.size(); k++) { 23 TreeNode *tmp = new TreeNode(i); 24 tmp->left = left[j]; 25 tmp->right = right[k]; 26 subtree.push_back(tmp); 27 } 28 } 29 } 30 return subtree; 31 } 32 vector<TreeNode *> generateTrees(int n) { 33 // Start typing your C/C++ solution below 34 // DO NOT write int main() function 35 return dfs(1, n); 36 } 37 };
C#
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 List<TreeNode> GenerateTrees(int n) { 12 return dfs(1, n); 13 } 14 public List<TreeNode> dfs(int start, int end) { 15 List<TreeNode> subTree = new List<TreeNode>(); 16 if (start > end) { 17 subTree.Add(null); 18 return subTree; 19 } 20 for (int i = start; i <= end; i++) { 21 List<TreeNode> left = dfs(start, i - 1); 22 List<TreeNode> right = dfs(i + 1, end); 23 for (int j = 0; j < left.Count; j++) { 24 for (int k = 0; k < right.Count; k++) { 25 TreeNode tmp = new TreeNode(i); 26 tmp.left = left[j]; 27 tmp.right = right[k]; 28 subTree.Add(tmp); 29 } 30 } 31 } 32 return subTree; 33 } 34 }