55、二叉树的下一个结点

一、题目

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

二、解法

 1 /*
 2 public class TreeLinkNode {
 3     int val;
 4     TreeLinkNode left = null;
 5     TreeLinkNode right = null;
 6     TreeLinkNode next = null;
 7 
 8     TreeLinkNode(int val) {
 9         this.val = val;
10     }
11 }
12 */
13 public class Solution {
14    public TreeLinkNode GetNext(TreeLinkNode pNode)
15     {
16         if(pNode == null)
17             return null;
18         if(pNode.right != null){//如果有右子树,则找右子树的最左节点
19             pNode = pNode.right;
20             while(pNode.left != null)
21                 pNode = pNode.left;
22             return pNode;
23         }
24         while(pNode.next != null){//没右子树,则找第一个当前节点是父节点左孩子的节点
25             if(pNode.next.left == pNode)
26                 return pNode.next;
27             pNode = pNode.next;
28         }
29         return null;//退到了根结点仍没找到,则返回null
30    }
31 }
原文地址:https://www.cnblogs.com/fankongkong/p/7460253.html