剑指 offer 树算法题:二叉树的下一个节点

题目描述:给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

分析

        迭代遍历法

        1. 若该节点 node 是 null,显然不存在下一节点;

        2. 若该节点 node 有右子树,下一节点为右子树中的最左节点,向左遍历直到左子树为空的节点即为下一节点;

         3. 若该节点 node 不存在右子树,则向上不断遍历父节点,直到当前节点的父节点的左孩子是该节点,返回此父节点; 若找不到(遍历到根节点),说明节点 node 已是中序遍历的最后一个节点。返回 null。

求解

class TreeLinkNode {
  val: number;
  left: TreeLinkNode | null;
  right: TreeLinkNode | null;
  next: TreeLinkNode | null;
  constructor(val?: number, left?: TreeLinkNode | null, right?: TreeLinkNode | null, next?: TreeLinkNode | null) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
    this.next = next === undefined ? null : next;
  }
}

// 遍历
function GetNext(node: TreeLinkNode | null) {
  // 该节点 null 不存在下一节点
  if (node === null) return null;
  if (node.right !== null) {
    // 该节点有右子树,下一节点为右子树中的最左节点
    let nextNode = node.right;
    while (nextNode.left !== null) {
      // 向左遍历直到左子树为空
      nextNode = nextNode.left;
    }
    return nextNode;
  }
  // 该节点没有右子树
  while (node.next !== null) {
    // 向上不断找父节点
    if (node.next.left === node) {
      // 直到当前节点的父节点的左孩子是该节点,返回当前节点父节点
      return node.next;
    }
    node = node.next;
  }
  // 找到根节点,其没有父节点,说明 node 是中序遍历的最后一个节点
  return null;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

薛定谔的猫96

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值