2019-11-02 12:07:41 +08:00
|
|
|
|
# 8. 二叉树的下一个结点
|
|
|
|
|
|
2019-11-02 23:29:42 +08:00
|
|
|
|
## 题目链接
|
|
|
|
|
|
|
|
|
|
[牛客网](https://www.nowcoder.com/practice/9023a0c988684a53960365b889ceaf5e?tpId=13&tqId=11210&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
## 题目描述
|
|
|
|
|
|
2019-11-02 23:29:42 +08:00
|
|
|
|
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回 。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public class TreeLinkNode {
|
|
|
|
|
|
|
|
|
|
int val;
|
|
|
|
|
TreeLinkNode left = null;
|
|
|
|
|
TreeLinkNode right = null;
|
2019-11-02 23:29:42 +08:00
|
|
|
|
TreeLinkNode next = null; // 指向父结点的指针
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
TreeLinkNode(int val) {
|
|
|
|
|
this.val = val;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## 解题思路
|
|
|
|
|
|
2019-11-02 23:29:42 +08:00
|
|
|
|
我们先来回顾一下中序遍历的过程:先遍历树的左子树,再遍历根节点,最后再遍历右子树。所以最左节点是中序遍历的第一个节点。
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
void traverse(TreeNode root) {
|
|
|
|
|
if (root == null) return;
|
|
|
|
|
traverse(root.left);
|
|
|
|
|
visit(root);
|
|
|
|
|
traverse(root.right);
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
2019-12-06 10:11:23 +08:00
|
|
|
|
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ad5cc8fc-d59b-45ce-8899-63a18320d97e.gif" width="300px"/> </div><br>
|
2019-11-02 23:29:42 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2019-11-02 12:07:41 +08:00
|
|
|
|
① 如果一个节点的右子树不为空,那么该节点的下一个节点是右子树的最左节点;
|
|
|
|
|
|
2019-12-06 10:11:23 +08:00
|
|
|
|
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/7008dc2b-6f13-4174-a516-28b2d75b0152.gif" width="300px"/> </div><br>
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
② 否则,向上找第一个左链接指向的树包含该节点的祖先节点。
|
|
|
|
|
|
2019-12-06 10:11:23 +08:00
|
|
|
|
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/094e3ac8-e080-4e94-9f0a-64c25abc695e.gif" width="300px"/> </div><br>
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public TreeLinkNode GetNext(TreeLinkNode pNode) {
|
|
|
|
|
if (pNode.right != null) {
|
|
|
|
|
TreeLinkNode node = pNode.right;
|
|
|
|
|
while (node.left != null)
|
|
|
|
|
node = node.left;
|
|
|
|
|
return node;
|
|
|
|
|
} else {
|
|
|
|
|
while (pNode.next != null) {
|
|
|
|
|
TreeLinkNode parent = pNode.next;
|
|
|
|
|
if (parent.left == pNode)
|
|
|
|
|
return parent;
|
|
|
|
|
pNode = pNode.next;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
```
|