zoukankan      html  css  js  c++  java
  • LC 894. All Possible Full Binary Trees

    full binary tree is a binary tree where each node has exactly 0 or 2 children.

    Return a list of all possible full binary trees with N nodes.  Each element of the answer is the root node of one possible tree.

    Each node of each tree in the answer must have node.val = 0.

    You may return the final list of trees in any order.

     

    Example 1:

    Input: 7
    Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]
    Explanation:

    Runtime: 104 ms, faster than 53.23% of C++ online submissions for All Possible Full Binary Trees.

    用map来优化。

    class Solution {
    private:
      unordered_map<int,vector<TreeNode*>> mp;
    public:
      vector<TreeNode*> allPossibleFBT(int N) {
        vector<TreeNode*> ret, leftvec, rightvec;
        if(N & 1 == 0 || N <= 0) return ret;
        return helper(N);
      }
      vector<TreeNode*> helper(int N){
        vector<TreeNode*> leftvec, rightvec, ret;
        if(mp.count(N)) return mp[N];
        if(N == 1) return {new TreeNode(0)};
        for(int i=1; i < N; i+=2){
          leftvec = helper(i);
          rightvec = helper(N - i -1);
          //cout << leftvec.size() << rightvec.size() << endl;
          for(int l = 0; l<leftvec.size();l++){
            for(int r = 0; r<rightvec.size();r++){
              TreeNode* tmp = new TreeNode(0);
              tmp->left = leftvec[l];
              tmp->right = rightvec[r];
              ret.push_back(tmp);
            }
          }
        }
        //cout << ret.size() << endl;
        mp[N] = ret;
        return ret;
      }
    };
  • 相关阅读:
    关于面向对象
    关于内存的划分和传引用传参数的区别
    关于目前我们专业的各种发展方向
    关于C语言底层
    关于游戏行业目前的形势
    关于jsp,javascript,php等语言
    鼠标滑动图片变大
    在Linux环境下mysql的root密码忘记解决方法
    百度网盘
    bootsrtap 主题元素
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10180340.html
Copyright © 2011-2022 走看看