【问题标题】:My check for whether a graph is a Binary Tree always returns false我检查一个图是否是二叉树总是返回 false
【发布时间】:2019-12-06 19:16:13
【问题描述】:

我有这个中等水平的问题,甚至无法考虑如何解决这个问题,我的解决方案可能有点矫枉过正,因为我不知道如何遍历数组中的一堆数字来检查它是否是是否是二叉树。无论如何,程序总是返回false

如果你对这个问题有更好的答案就完美了

让函数TreeConstructor(strArr) 获取存储在strArr 中的字符串数组,该数组将包含以下格式的整数对 (i1, i2),其中 i1 代表树中的一个子节点,第二个整数 i2表示它是 i1 的父级。例如如果strArr["(1,2)", "(2,4)", "(7,2)"]

    4 
   /
  2
 / \
1   7

你可以看到它形成了一个正确的二叉树。在这种情况下,您的程序应该返回字符串 true,因为可以形成有效的二叉树。如果整数对不能形成正确的二进制,则返回字符串 false。树中的所有整数都是唯一的,这意味着树中只能有一个具有给定整数值的节点

示例

input: ["(1,2)", "(2,4)", "(5,7)", "(7,2)", "(9,5)"]
output: true


input ["(1,2)", "(1,3)"]
output: false

我尝试了一下,但它总是返回 false。我的代码很可能是矫枉过正。

class Node {
  // The constructor
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
  // Basic insert node
  insert(value) {
    let currentNode = this;
    while (true) {
      if (value < currentNode.value) {
        if (currentNode.left === null) {
          currentNode.left = new Node(value);
          break;
        } else {
          currentNode = currentNode.left;
        }
      } else {
        if (currentNode.right === null) {
          currentNode.right = new Node(value);
          break;
        } else {
          currentNode = currentNode.right;
        }
      }
    }
    return currentNode
  }
    // check if BST is valid or not
    isValidBST(node, min = null, max = null) {
    if (!node) return true;
    if (max !== null && node.value >= max) {
      return false;
    }
    if (min !== null && node.value <= min) {
      return false;
    }
    const leftSide = this.isValidBST(node.left, min, node.value);
    const rightSide = this.isValidBST(node.right, node.value, max);
    return leftSide && rightSide;
  }
}

// Convert the strings to a number 
function convertListToNumber(str, i) {
  return str[i].split('(').join('').split(')').join('').split(',').join('')
}

这是主要功能

function TreeConstructorTwo(strArr) { 
  // code goes here  
  startValueFromList = convertListToNumber(strArr, 0)
  // Parent Node here
  startParentNode = startValueFromList[1];
  // Child Node here
  startChildNode = startValueFromList[0];
  // Add parent Node and childNode
  node = new Node(startParentNode);
  node.insert(startChildNode);
  // Loop through the entire array
  for (i = 1; i < strArr.length; i++) {
    myListValue = convertListToNumber(strArr, i);
    console.log(myListValue.length)
    // Loop the "12" in the string and convert it to a number
    for (j = 0; j < myListValue.length; j++) {
       node.insert(myListValue[j])
    }
    parentNode = Number(myListValue[0])
  }
  // Check if the BST is valid or not
  return node.isValidBST(node)
}

// keep this function call here 
console.log(TreeConstructorTwo(["(1,2)", "(2,4)", "(5,7)", "(7,2)", "(9,5)"]));

【问题讨论】:

  • 阅读ericlippert.com/2014/03/05/how-to-debug-small-programs 了解调试代码的技巧。
  • 你甚至需要构建树来验证它吗?关注 BST 必须展示的属性(孩子的数量等)。输入没有指定什么是左什么是右,所以只要你有正确的数字,你就可以有效地安排它们。树不必是完整的或平衡的。
  • 你有 1) 一个问题,2) 一些示例,3) 一些代码。你缺少的是一种算法。
  • @PartyLich 你对如何验证有什么建议吗?想不出任何东西,因此我为什么左右做可能是为了验证树
  • 我的意思是你跳过了这个过程中最重要的部分。您应该设计一个算法,并在问题中提出该算法。然后我们可以讨论算法。目前,我必须对代码进行逆向工程以尝试猜测您的算法是什么。

标签: javascript algorithm data-structures


【解决方案1】:

最近我已经完成了这个任务的解决方案,请在下面查看我的解决方案:

const isBinaryTree = (array) => {
  const getChildrenNode = (node) => node.slice(1, 2);
  const childrenNodes = array.map(x => getChildrenNode(x));
  const isChildrenNodesIsUnique = (array) => array.length === new Set(array).size;
  
  return isChildrenNodesIsUnique(childrenNodes);
};


console.log(isBinaryTree(["(1,2)", "(2,4)", "(5,7)", "(7,2)", "(9,5)"]));
console.log(isBinaryTree(["(1,2)", "(1,3)"]));

【讨论】:

  • 它不适用于["(1,2)", "(3,2)", "(2,12)", "(5,2)"]
【解决方案2】:

您似乎误解了这项任务。当表示的树是二叉树而不一定是二叉搜索树时,该函数应该返回true。

您的代码正在从第一个元素创建一棵树,然后将任何下一个节点插入到该树中,并保持二分搜索属性,而没有考虑输入中的对要求第一个是直接子元素第二个。 (您的变量parentNode 不用于任何用途)

相反,您应该只查看输入中给出的表示的子父关系,并使用该信息来构建图形。最后,您应该验证该图是否代表binary tree。想一想二叉树的显着特征是什么以及如何验证它们。

注意:我会用首字母小写字母命名函数,因为通常的做法是为类名保留首字母大写。

【讨论】:

  • 没有节点(因此没有边)仍然是有效的二叉树吗?有些人可能会说是的。您的“只有一个节点没有父节点”的标准可能需要稍作调整。
  • 正确:改写。
  • 我希望我能像你一样解决问题@trincot
【解决方案3】:
function isBinaryTree(tree) {

    isBinary = 0; 
  
    childs = tree.map(node => {
        return node.substr(1, 1)
    });
  
    parents = tree.map(node => {
        return node.substr(3, 1)
    });
    
    parents.map(parent => {
        if (!childs.includes(parent))
            isBinary++;
    });
  
    isBinary = isBinary == 1 ? true : false;
  
    return isBinary;

}

【讨论】:

    【解决方案4】:

    我通过在一个数组中收集父 ID 并检查是否有任何父 ID 存在两次以上来做到这一点。不知道会不会

    [“(1,2)”, “(3,2)”, “(2,12)”, “(5,2)”]

    因为 2 在该对的右侧出现了 3 次,所以它是错误的(根或叶节点不能有超过 2 个子节点)

    【讨论】:

      【解决方案5】:

      const isBinaryTree = (array) => {
      
        // find the parent child
        const parentChildFreq = (value) => {
      
          const charFreqency = {};
          for (let index = 0; index < value.length; index++) {
            if (charFreqency[value[index]]) {
              // if parent have more the 2 children then this is not binary-tree
              if (charFreqency[value[index]] >= 2) {
                return false;
              }
              charFreqency[value[index]] += 1;
            } else charFreqency[value[index]] = 1;
          }
          return true;
        };
      
        const isChildrenNodesIsUnique = (array) =>
          array.length === new Set(array).size;
      
        const childrenNodes = array.map((node) => node[1]);
      
        let parentsNodes = array.map((node) => node[3]);
        parentsNodes = Array.from(parentsNodes, Number);
        
      
        return isChildrenNodesIsUnique(childrenNodes) && parentChildFreq(parentsNodes)
          ? " \n Binary-tree"
          : "not-binary-tree";
      };
      
      console.log(isBinaryTree(["(1,2)", "(2,4)", "(5,7)", "(7,2)", "(9,5)"]));
      //console.log(isBinaryTree(["(1,2)", "(3,2)", "(2,12)", "(5,2)"]));

      【讨论】:

        猜你喜欢
        • 2015-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多