LeetCode: 894. All Possible Full Binary Trees
阿新 • • 發佈:2018-12-22
題目:894. All Possible Full Binary Trees(https://leetcode.com/problems/all-possible-full-binary-trees/description/).
這個問題是典型的遞迴問題,首先讀題之後可知有性質“完全二叉樹結點個數必定為奇數”。所以問題變簡單了點,如果輸入N為偶數,直接輸出空List即可。
對於一個有n個結點的完全二叉樹,其可以分解為有i個結點(i為奇數)的左子樹和n-i-1個結點的右子樹,所以只需遍歷i的取值即可!
class Solution { public List<TreeNode> allPossibleFBT(int N) { List<TreeNode> res = new ArrayList<>(); if (N == 1) { res.add(new TreeNode(0)); return res; } if (N % 2 == 0) { return res; } for (int i = 1; i < N; i = i + 2) { List<TreeNode> lns = allPossibleFBT(i); List<TreeNode> rns = allPossibleFBT(N - i - 1); for (TreeNode ln : lns) { for (TreeNode rn : rns) { TreeNode head = new TreeNode(0); head.left = ln; head.right = rn; res.add(head); } } } return res; } }