首页 > 编程语言 >It's possible to create a function auto generator this special test case binary tree from array

It's possible to create a function auto generator this special test case binary tree from array

时间:2023-01-31 18:24:21浏览次数:61  
标签:function case right generator binary tree key null left

It's possible to create a function auto generator this special test case binary tree from array in javascript?

I want to auto generate those test cases in my local env. I'm not asking the LeetCode problem's answer, please read my question first!

situation

generator the special test case binary tree for local testing, which isn't a search binary tree;

I have an array of nodes of a binary tree and wanted to create a special binary tree like the below image shows.

// nodes array
const root = [3,9,20,null,null,15,7]

enter image description here

I tried a few things and searched google, still can't find a solution;
is there any way to find a solution to this problem, please?

PS: I know that I can manually create it.


// created by manually
const specialTestCaseTree = {
  val: 3,
  left: {
    val: 9,
    left: null,
    right: null,
  },
  right: {
    val: 20,
    left: {
      val: 15,
      left: null,
      right: null,
    },
    right: {
      val: 7,
      left: null,
      right: null,
    },
  },
};

try

class TreeNode {
  constructor(val, left, right) {
    this.val = (val === undefined ? 0 : val);
    this.left = (left === undefined ? null : left);
    this.right = (right === undefined ? null : right);
  }
}

class BinaryTreeGenerator {
  constructor() {
    this.root = null;
    this.flag = `left`;
  }
  insert(key) {
    if(this.root === null) {
      this.root = new TreeNode(key);
    } else {
      this.insertNode(this.root, key)
    }
  }
  insertNode(node, key) {
    // ignore null
    if(key === null) {
      return;
    }
    // tree traversal(root=>left=>right)
    if(this.flag === `left`) {
      // left
      if(node.left === null) {
        node.left = new TreeNode(key);
        this.flag = `right`;
      } else {
        this.insertNode(node.left, key)
      }
    } else {
      // right
      if(node.right === null) {
        node.right = new TreeNode(key);
        this.flag = `left`;
      } else {
        this.insertNode(node.right, key)
      }
    }
  }
}

// testing

const tree = new BinaryTreeGenerator();

const arr = [3,9,20,null,null,15,7];

for (let key of arr) {
  tree.insert(key)
}

console.log(`tree =`, tree);
// ❌ not the wanted

references

https://leetcode.com/problems/maximum-depth-of-binary-tree/description/

(

标签:function,case,right,generator,binary,tree,key,null,left
From: https://www.cnblogs.com/xgqfrms/p/17080136.html

相关文章