二叉树的基础操作(Java)

 1 //1 二叉树的深度(在后序遍历的基础上进行 时间复杂度: O(n)) (即左右子树的最大深度加1)
2 public int getDepth(BiTNode node) 3 { 4 if(node == null) 5 return 0; 6 7 int count1, count2; 8 count1 = getDepth(node.lchild); 9 count2 = getDepth(node.rchild); 10 return max(count1, count2) + 1; 11 } 12 13 //2 给定结点的后继(Successor) 14 public int getSuccessor(BiTNode node) 15 { 16 BiTNode p; 17 18 if(node == node.parent.lchild || node == this.root) 19 { 20 if(node.rchild != null) 21 { 22 p = node.rchild; 23 while(p.lchild != null) 24 p = p.lchild; 25 return p; 26 } 27 else 28 return node.parent; 29 } 30 else if(node == node.parent.rchild) 31 { 32 if(node.rchild != null) 33 { 34 p = node.rchild; 35 while(p.lchild != null) 36 p = p.lchild; 37 return p; 38 } 39 else 40 { 41 p = node.parent; 42 while(p != this.root && p.parent.lchild != p) 43 p = p.parent; 44 return p == this.root ? null : p.parent; 45 } 46 } 47 }

猜你喜欢

转载自www.cnblogs.com/Huayra/p/10808070.html
今日推荐