• Java 数据结构教程

删除树中的叶子节点



遍历树中的每个节点,验证它是否有左子节点、右子节点或两者都有。如果它没有任何子节点,则删除该特定节点。

示例

class Node{
   int data;
   Node leftNode, rightNode;
   
   Node() {
      leftNode = null;
      rightNode = null;     
      this.data = data;
   }
   Node(int data) {
      leftNode = null;
      rightNode = null;     
      this.data = data;
   }   
   int getData() {
      return this.data;	   
   }
   Node getleftNode() {
      return this.leftNode;	   
   }	   
   Node getRightNode() {
      return this.leftNode;	   
   }
   void setData(int data) {
      this.data = data; 
   }		   
   void setleftNode(Node leftNode) {
      this.leftNode = leftNode;	   
   }
   void setRightNode(Node rightNode) {
      this.leftNode = rightNode;	      
   }
}
public class RemovingLeaf {
   public static void main(String[] args) {
      Node node = new Node(50);
      node.leftNode = new Node(60);
      node.leftNode.leftNode = new Node(45);
      node.leftNode.rightNode = new Node(64);

      node.rightNode = new Node(60);
      node.rightNode.leftNode = new Node(45);
      node.rightNode.rightNode = new Node(64);
      
      node.leftNode.leftNode.leftNode = new Node(96);
      System.out.println("Contents of the tree:");
      preOrder(node);	   
      removeLeaves(node);
      System.out.println();
      System.out.println("Contents of the tree after removing leafs:");
      preOrder(node);
   }
   public static void removeLeaves(Node node) {
      if (node.leftNode != null) { // tests left root
         if (node.leftNode.leftNode == null && node.leftNode.rightNode == null) { 
            node.leftNode = null; // delete
         } else {
            removeLeaves(node.leftNode);
         }
      }
   }
   public static void preOrder(Node root) {
      if(root !=null) {
         System.out.print(root.data+" ");
         preOrder(root.leftNode);
         preOrder(root.rightNode);    	  
      }      	   
   }
}

输出

Contents of the tree:
50 60 45 96 64 60 45 64 
Contents of the tree after removing leafs:
50 60 45 64 60 45 64
广告