[Algorithm] Given the root to a binary tree, return the deepest node

本文介绍了一种使用递归方法在二叉树中找到最深节点的算法。通过创建节点和二叉树,利用递归函数遍历树的左右子叶,直到到达没有子叶的节点,返回其深度和节点值。

By given a binary tree, and a root node, find the deepest node of this tree.

 

We have way to create node:

function createNode(val, left = null, right = null) {
  return {
    val,
    left,
    addLeft(leftKey) {
      return (this.left = leftKey ? createNode(leftKey) : null);
    },
    right,
    addRight(rightKey) {
      return (this.right = rightKey ? createNode(rightKey) : null);
    }
  };
}

 

Way to create tree:

function createBT(rootKey) {
  const root = createNode(rootKey);
  return {
    root,
    deepest(node) {
      // code goes here
    }
  };
}

 

Way to construct tree:

const tree = createBT("root");
const root = tree.root;
const left = root.addLeft("left");
root.addRight("right");

const leftleft = left.addLeft("left.left");
const leftleftleft = leftleft.addLeft("left.left.left");
const leftright = left.addRight("left.right");
leftright.addLeft("left.right.left");

 

The way to solve the problem is recursive calling the 'deepest' function for node's left and right leaf, until we reach the base case, which is the node that doesn't contian any left or right leaf.

function createNode(val, left = null, right = null) {
  return {
    val,
    left,
    addLeft(leftKey) {
      return (this.left = leftKey ? createNode(leftKey) : null);
    },
    right,
    addRight(rightKey) {
      return (this.right = rightKey ? createNode(rightKey) : null);
    }
  };
}

function createBT(rootKey) {
  const root = createNode(rootKey);
  return {
    root,
    deepest(node) {
      function helper(node, depth) {
        if (node && !node.left && !node.right) {
          return {
            depth,
            node
          };
        }

        if (node.left) {
          return helper(node.left, depth + 1);
        } else if (node.right) {
          return helper(node.right, depth + 1);
        }
      }

      const { depth: ld, node: ln } = helper(root.left, 1);
      const { depth: rd, node: rn } = helper(root.right, 1);

      const max = Math.max(ld, rd);
      if (max === ld) {
        return { depth: ld, node: ln.val };
      } else {
        return { depth: rd, node: rn.val };
      }
    }
  };
}

const tree = createBT("root");
const root = tree.root;
const left = root.addLeft("left");
root.addRight("right");

const leftleft = left.addLeft("left.left");
const leftleftleft = leftleft.addLeft("left.left.left");
const leftright = left.addRight("left.right");
leftright.addLeft("left.right.left");

console.log(tree.deepest(root)); // {depth: 3, node: "left.left.left"}

 

转载于:https://www.cnblogs.com/Answer1215/p/10513146.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值