递归二叉树

1、基本概念

(1)节点:结点包含数据和指向其它节点的指针。

(2)根节点:树第一个结点称为根节点。

(3)结点的度:结点拥有的子节点个数。

(4)叶节点:没有子节点的节点(度为0)。

(5)父子节点:一个节点father指向另一个节点child,则child为孩子节点,father为父亲节点。

(6)兄弟节点:具有相同父节点的节点互为兄弟节点。

(7)节点的祖先:从根节点开始到该节点所经的所有节点都可以称为该节点的祖先。

(8)子孙:以某节点为根的子树中任一节点都称为该节点的子孙。

(9)树的高度:树中距离根节点最远节点的路径长度。

2、基本原理

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

  利用层数控制迭代次数。

  依次递归第二段的内容。

3,3层二叉树代码的实现

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);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42775190/article/details/81192154