二叉树的下一个节点
二叉树的下一个结点
http://www.nowcoder.com/questionTerminal/9023a0c988684a53960365b889ceaf5e
一. 思路
通过给出的节点的父节点指针,一直找到该二叉树的根节点,再用中序遍历弄个序列,直接for循环访问指定节点的下一个节点即可。要注意中序遍历序列的最后一个节点的后面没有节点。
二. 代码
import java.util.*;
/*
public class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
TreeLinkNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<TreeLinkNode> list = new ArrayList<>();
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
TreeLinkNode node = pNode;
//找到根节点
while (node.next != null) {
node = node.next;
}
//递归中序遍历
inOrder(node);
for (int i = 0; i < list.size(); i++) {
if (pNode == list.get(i)) {
return i == list.size()-1 ? null : list.get(i+1);//处理最后一个节点的后面没有节点,只能返回null
}
}
return null;
}
public void inOrder(TreeLinkNode node) {
if (node != null) {
inOrder(node.left);
list.add(node);
inOrder(node.right);
}
}
}三. 总结
树的中序遍历序列,采用递归弄出来,需要借助一个ArrayList