GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — algorithm/src/offer/InOrderNextTreeNode8.java at main · duktig666/algorithm

Expand file tree

/

InOrderNextTreeNode8.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
71 lines (64 loc) · 2.36 KB
/

InOrderNextTreeNode8.java

Copy path

File metadata and controls

71 lines (64 loc) · 2.36 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package offer;
/**
* description:二叉树的下一个节点(中序遍历)
* <p>
* 情况分析:
* 1. 如果一个节点的右子树不为空(有右子树),那么该节点的下一个节点是右子树的最左节点<br>
* 2. 如果一个节点的右子树为空(无右子树)<br>
* ① 当前节点是父节点的左子节点,那么下一个节点是其父节点<br>
* ② 当前节点是父节点的右子节点,那么下一个节点需要沿父节点向上遍历,直到找到一个是它父节点的左子节点的节点(可能存在没有下一个节点,即最右节点)<br>
* 这两种情况其实可以总结为<br>
* 如果一个节点的右子树为空,那么需要沿着父节点的指针一直向上遍历,知道找到一个是它父节点的左子节点的节点。
* 如果这样的节点存在,那么这个节点的父节点就是我们要找的下一个节点。
*
* @author RenShiWei
* Date: 2021/8/7 9:15
**/
public class InOrderNextTreeNode8<T> {
private static class TreeNode<T> {
T val;
TreeNode<T> left;
TreeNode<T> right;
TreeNode<T> parent;
TreeNode(T val) {
this.val = val;
}
}
/**
* 寻找二叉树的下一个节点(中序遍历)
*
* @param pNode 当前二叉树节点
* @return 下一个节点
*/
public TreeNode<T> getNext(TreeNode<T> pNode) {
if (pNode == null) {
return null;
}
if (pNode.right != null) {
//有右子树
TreeNode<T> rNode = pNode.right;
//找右子树的最左节点
while (rNode.left != null) {
rNode = rNode.left;
}
return rNode;
} else {
/*
当前节点无右子树,分两种情况
情况1:当前节点是父节点的左子节点,那么下一个节点是其父节点
if (pNode == pNode.parent.left) {
return pNode.parent;
}
可以总体整合如下技术:
*/
while (pNode.parent != null) {
TreeNode<T> parentNode = pNode.parent;
if (parentNode.left == pNode) {
return parentNode;
}
pNode = pNode.parent;
}
}
return null;
}
}
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.