【leetcode】95.(Medium)Unique Binary Search Tree II

解题思路:
这道题的意思是,给定n,求出所有包含1-n值的中序遍历树


提交代码:

class Solution {
	public List<TreeNode> generateTrees(int n) {
		List<TreeNode> res=new ArrayList<TreeNode>();
		if(n<1)	return res;
		return generateTrees(1, n);
	}

	private List<TreeNode> generateTrees(int left, int right) {
		List<TreeNode> res = new ArrayList<TreeNode>();
		if (left > right) {
			res.add(null);
			return res;
		}

		for (int i = left; i <= right; i++) {
			List<TreeNode> leftRes = generateTrees(left, i - 1);
			List<TreeNode> rightRes = generateTrees(i + 1, right);
			for (int j = 0; j < leftRes.size(); j++) {
				for (int k = 0; k < rightRes.size(); k++) {
					TreeNode root = new TreeNode(i);
					root.left = leftRes.get(j);
					root.right = rightRes.get(k);
					res.add(root);
				}
			}
		}
		return res;
	}
}

运行结果:
【leetcode】95.(Medium)Unique Binary Search Tree II_第1张图片

你可能感兴趣的:(leetcode)