(18) 中序遍历的下一个结点

摘自剑指Offer

一、题目描述

  • 给定一个节点
  • 在中序遍历中输出它的下一个节点

 

二、Code

1、思路

  • 首先要明确中序遍历的顺序   左->根->右

  • 若给定结点有右节点,则寻找右节点的左结点,直到没有左节点为止
  • 否则寻找父节点。
  • 若父节点的左节点为本节点,则输出父节点。
  • 若父节点的右节点为本节点则接着往上。

 

2、Code

 1 package algorithm;
 2 
 3 /**
 4  * Created by adrian.wu on 2019/3/26.
 5  */
 6 public class InOrderNextNode {
 7     static class BinaryTreeNode {
 8         BinaryTreeNode parent, left, right;
 9         int val;
10 
11         public BinaryTreeNode(int val) {
12             this.val = val;
13             parent = null;
14             left = null;
15             right = null;
16         }
17     }
18 
19     public static BinaryTreeNode inNextNode(BinaryTreeNode node) {
20         if (node == null) return null;
21 
22         if (node.right != null) {
23             BinaryTreeNode rightStopNode = node.right;
24             while (rightStopNode.left != null) rightStopNode = rightStopNode.left;
25             return rightStopNode;
26         }
27 
28         BinaryTreeNode parent = node;
29         while (parent != null) {
30             if (parent.left == node) return parent;
31             node = parent;
32             parent = parent.parent;
33         }
34         return null;
35     }
36 }

 

转载于:https://www.cnblogs.com/ylxn/p/10601214.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值