2种BinaryTree的Testcase写法(输入输出模板)

以 236. Lowest Common Ancestor of a Binary Tree 为例:

// Define a simple binary tree node structure
function TreeNode(val) {
  this.val = val;
  this.left = this.right = null;
}

// Create a binary tree
//      3
//     / \
//    5   1
//   / \ / \
//  6  2 0  8
//    / \
//   7   4
const root = new TreeNode(3);
root.left = new TreeNode(5);
root.right = new TreeNode(1);
root.left.left = new TreeNode(6);
root.left.right = new TreeNode(2);
root.right.left = new TreeNode(0);
root.right.right = new TreeNode(8);
root.left.right.left = new TreeNode(7);
root.left.right.right = new TreeNode(4);

// Nodes for which we want to find the LCA
const p = root.left; // Node with value 5
const q = root.left.right.right; // Node with value 4

var lowestCommonAncestor = function (root, p, q) {
  function dfs(root, q, p) {
    if (root === q || root === p || root === null) return root;
    let left = dfs(root.left, q, p);
    let right = dfs(root.right, q, p);
    if (left !== null && right !== null) return root;
    else if (left !== null && right === null) return left;
    else if (left === null && right !== null) return right;
    else return null;
  }
  return dfs(root, q, p);
};

// Call the lowestCommonAncestor function
const lca = lowestCommonAncestor(root, p, q);

// Output the result
console.log(
  `The lowest common ancestor of nodes ${p.val} and ${q.val} is node with value ${lca.val}.`
);


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

// Create a binary tree
//      3
//     / \
//    5   1
//   / \ / \
//  6  2 0  8
//    / \
//   7   4
const root = new TreeNode(
  3,
  new TreeNode(
    5,
    new TreeNode(6),
    new TreeNode(2, new TreeNode(7), new TreeNode(4))
  ),
  new TreeNode(1, new TreeNode(0), new TreeNode(8))
);

const p = root.left; // Node with value 5
const q = root.left.right.right; // Node with value 4

// Lowest Common Ancestor function
var lowestCommonAncestor = function (root, p, q) {
  function dfs(root, q, p) {
    if (root === q || root === p || root === null) return root;
    let left = dfs(root.left, q, p);
    let right = dfs(root.right, q, p);
    if (left !== null && right !== null) return root;
    else if (left !== null && right === null) return left;
    else if (left === null && right !== null) return right;
    else return null;
  }
  return dfs(root, q, p);
};

// Find the LCA
const lca = lowestCommonAncestor(root, p, q);

console.log(
  `The lowest common ancestor of nodes ${p.val} and ${q.val} is node ${lca.val}.`
);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值