zoukankan      html  css  js  c++  java
  • convert tree to completed K siblings tree

    就是一棵任意形状的树,给你一个数k,让你把这棵数变成每个节点只有k或者0个孩子的结构,之前某节点孩子不可以变成该节点的祖先,但是可以是兄弟
    由于第一题扣细节逻辑花了40分钟(主要是我一开始没有理解面试官的困惑,然后一步一步的解释来着),第二题就说了个思路(我的想法就是层序遍历然后把对应是一层的节点放到一个list里面,然后再把list变回树,大家有没有更好的思路)

    public void childrenK(TreeNode root, int k) {
            if (root == null) {
                return;
            }
            Queue<TreeNode> q1 = new LinkedList<>();
            q1.add(root);
            ArrayList<TreeNode> list = new ArrayList<>();
            while (!q1.isEmpty()) {
                int size = q1.size();
               
                for (int i = 0; i < size; i++) {
                    TreeNode cur = q1.poll();
              list.add(cur); ArrayList<TreeNode> curChild = cur.children(); if (curChild != null || curChild.size() != 0) q1.addAll(curChild); } } TreeNode root = new TreeNode(list.remove(0)); Queue<TreeNode> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { int size = q.size(); for (int i = 0; i < size; i++) { TreeNode cur = q.poll(); for (int j = 0; j < k; j++) { if (list.size() > 0) { TreeNode chil = new TreeNode(list.remove(0); cur.children.add(chil)); q.add(chil); } } }

      

  • 相关阅读:
    type 、instanceof、in 和 hasOwnproperty
    从代码中抽离数据的原则
    NSNotificationCenter 通知中心传值
    imageView添加阴影和边框
    block的基本使用
    内存管理总结
    把color转成image的方法
    Instruments检测解决内存泄露以及进行性能测试
    Xcode7 修改项目名完全攻略
    UITextField的使用总结
  • 原文地址:https://www.cnblogs.com/apanda009/p/7923867.html
Copyright © 2011-2022 走看看