剑指offer--二叉树的下一个结点

来源:互联网 发布:魔兽1.12数据库 声望 编辑:程序博客网 时间:2024/04/29 21:05

题目描述

给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
[java] view plain copy
  1. public static class TreeLinkNode {  
  2.         int val;  
  3.         TreeLinkNode left = null;  
  4.         TreeLinkNode right = null;  
  5.         TreeLinkNode next = null;  
  6.   
  7.         TreeLinkNode(int val) {  
  8.             this.val = val;  
  9.         }  
  10.     }  
  11.       
  12.     TreeLinkNode GetNext(TreeLinkNode pNode){  
  13.         if(pNode==nullreturn null;  
  14.         if(pNode.next==null){//如果是根节点,查找右子树的最左节点(如果存在)        
  15.             if(pNode.right==nullreturn null;  
  16.             pNode = pNode.right;  
  17.             while(pNode.left!=null) pNode=pNode.left;  
  18.             return pNode;  
  19.         }else if(pNode.next.left==pNode){//如果是父节点的左节点,当其右节点不存在时,返回父节点;否则返回右子树最左节点  
  20.             if(pNode.right==nullreturn pNode.next;  
  21.             pNode = pNode.right;  
  22.             while(pNode.left!=null) pNode=pNode.left;  
  23.             return pNode;  
  24.         }else if(pNode.next.right==pNode){//如果是父节点的右节点,当其右节点存在,返回右节点;否则返回最非右父节点之父(如果过程循环到根节点,返回空)  
  25.             if(pNode.right!=nullreturn pNode.right;         
  26.             while(pNode.next!=null && pNode.next.right==pNode) pNode=pNode.next;  
  27.             if(pNode.next==nullreturn null;             
  28.             return pNode.next;  
  29.         }  
  30.         return null;  
  31.     }  


原文链接http://blog.csdn.net/crazy__chen/article/details/45101775

原创粉丝点击