zoukankan      html  css  js  c++  java
  • 二叉树的递归实现(java)

      这里演示的二叉树为3层。

      递归实现,先构造出一个root节点,先判断左子节点是否为空,为空则构造左子节点,否则进入下一步判断右子节点是否为空,为空则构造右子节点。

      利用层数控制迭代次数。

      依次递归第二段的内容。

      下面是代码,很简单,耐心看看就懂了。

      

    package Construct;
    
    public class ConstructTree {
    	
    	private int count = 0;
    
    	class Node {
    		int i;
    		Node left;
    		Node right;
    		public Node(int i) {
    			this.i = i;
    		}
    	}
    	
    	
    	public static void main(String[] args) throws Exception {
    		ConstructTree ct = new ConstructTree();
    		ct.startRun(3);
    	}
    	
    	public void startRun(int n) {
    		Node root = new Node(count++);
    		System.out.println(count - 1+" root "+n);
    		Node current = root;
    		Construct(current,n - 1);
    	}
    	
    	public void Construct(Node current, int n) {
    		if(n > 0) {
    			if(current.left == null) {
    				current.left = new Node(count++);
    				System.out.println(count - 1+" left "+n);
    				Construct(current.left, n - 1);
    			}
    			if(current.right == null) {
    				current.right = new Node(count++);
    				System.out.println(count - 1+" right  "+n);
    				Construct(current.right, n - 1);
    			}
    		}
    	}
    }
    

       输出:(下面输出对应值)节点的数据  左节点/右节点  层数

    0  root  3
    1 left 2
    2 left 1
    3 right  1
    4 right  2
    5 left 1
    6 right  1
    
  • 相关阅读:
    网络协议 7
    网络协议 6
    PHP 扩展管理
    网络协议 5
    什么是DevOps?
    C# Web API Modify Post Data Size Limit
    Redis 数据变化通知服务实践
    .net 相关性能计数器丢失问题解决方案
    为什么要DevOps?
    分布式服务发现的几种模型
  • 原文地址:https://www.cnblogs.com/xiangxi/p/4969701.html
Copyright © 2011-2022 走看看