二叉树的下一个节点(java版)

xiaoxiao2021-02-27  211

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


【解题思路1】暴力解法 //1.若给定的节点pNode的右子树不为空,则中序遍历的下一个节点为其右子树的最左侧节点。 //2.若给定的节点pNode的右子树为空,分两种情况。一种是左子树不为空,此时中序遍历的下一个节点为其父节点。另一种情况是,其为叶子节点,左右子树都为空。 //3.当其为叶子节点的时候,需要判断是左叶子节点还是右叶子节点。若是左叶子节点,则中序遍历的下一个节点即为其父节点;若为右叶子节点,则中序遍历的下一个节点,应为其父节点的父节点。(排除特殊情况) //4.注意到在第三条中,有可能出现特殊情况。比如二叉树只有一个节点pNode的情况;二叉树是单枝斜树的情况;

public class Solution { public TreeLinkNode GetNext(TreeLinkNode pNode) { if(pNode == null){ return null; } //右子树不为空的情况 if(pNode.right!=null){ TreeLinkNode inx = pNode.right; while(inx !=null){ if(inx.left != null){ inx = inx.left; }else{ break; } } return inx; }else if(pNode.left !=null && pNode.right ==null){ //左子树不为空,右子树为空的情况 return pNode.next; }else{ //左右子树都为空的情况,即叶子节点的情况 if(pNode.next==null){ return null; //二叉树只有pNode一个节点,即pNode即是叶子节点,也是根节点,即无父节点 } if(pNode.next.left == pNode){ return pNode.next; //pNode是左叶子节点的情况 }else{ //pNode是右叶子节点的情况,先找到根节点 TreeLinkNode inx = pNode.next; while(inx != null){ if(inx.next != null){ inx = inx.next; }else{ break; } } if(inx == pNode){ return null; //斜树的情况 } while(inx != null){ if(inx.right != null){ inx = inx.right; }else{ break; } } if(inx == pNode){ return null; //中序遍历最后一个节点的情况 }else{ return pNode.next.next; } } } } }

【解题思路2】

结合图,我们可发现分成两大类: 1、有右子树的,那么下个结点就是右子树最左边的点;(eg:D,B,E,A,C,G) 2、没有右子树的,也可以分成两类: a)是父节点左孩子(eg:N,I,L) ,那么父节点就是下一个节点 ; b)是父节点的右孩子(eg:H,J,K,M)找他的父节点的父节点的父节点…直到当前结点是其父节点的左孩子位置。如果没有eg:M,那么他就是尾节点。 3.该图和方案由牛客“小河沟大河沟”提供,源码为“weizier”提供。

链接:https://www.nowcoder.com/questionTerminal/9023a0c988684a53960365b889ceaf5e 来源:牛客网 public class Solution { TreeLinkNode GetNext(TreeLinkNode node) { if(node==null) return null; if(node.right!=null){ //如果有右子树,则找右子树的最左节点 node = node.right; while(node.left!=null) node = node.left; return node; } while(node.next!=null){ //没右子树,则找第一个当前节点是父节点左孩子的节点 if(node.next.left==node) return node.next; node = node.next; } return null; //退到了根节点仍没找到,则返回null } }
转载请注明原文地址: https://www.6miu.com/read-12371.html

最新回复(0)