node 节点
public class Node{ private Node left; private Node right; private int data; public Node(int data){ this.data = data; } public void setLChild(Node left){ this.left = left; } public void setRChild(Node right){ this.right = right; } public void setData(int data){ this.data = data; } public int getData(){ return this.data; } public Node getLChild(){ return this.left; } public Node getRChild(){ return this.right; } }
二叉树tree 结构
/** * Created by pb_li on 2019/1/16. */ public class Tree { /** * 有一个根节点 * */ public Node root; public static int index; public Node CreateBTree(int[] a) { Node root = null; if (a[index] != '#') { root = new Node(a[index]); index++; root.setLChild(CreateBTree(a)); index++; root.setRChild(CreateBTree(a)); } return root; } //先序遍历 public void prevOrder(Node root) { if (root == null) { return; } System.out.print(root.getData() + ","); prevOrder(root.getLChild()); prevOrder(root.getRChild()); } //中序遍历 public void inOrder(Node root) { if (root == null) { return; } inOrder(root.getLChild()); System.out.print(root.getData() + ","); inOrder(root.getRChild()); } //后序遍历 public void postOrder(Node root) { if (root == null) { return; } postOrder(root.getLChild()); postOrder(root.getRChild()); System.out.print(root.getData() + ","); } //获得高度 public int getHeight() { Node cur = this.root; int height = 0; while (cur != null) { cur = cur.getLChild(); height++; } return height; } //获得叶子数 public int getLeaf(Node root) { if (root == null) { return 0; } else if (root.getLChild() == null && root.getLChild() == null) { System.out.println("Leaf:" + root.getData()); return 1; } return getLeaf(root.getLChild()) + getLeaf(root.getRChild()); } //获得第K层节点数 public int getNodeKNum(Node root, int k) { if (k == 1) { if (root == null) { return 0; } System.out.println("K Node:" + root.getData()); return 1; } return getNodeKNum(root.getLChild(), k - 1) + getNodeKNum(root.getRChild(), k - 1); } //查找某个节点 public Node findNode(Node root, int x) { if (root == null) { return null; } else if (root.getData() == x) { return root; } Node leftNode = findNode(root.getLChild(), x); if (null != leftNode) { return leftNode; } Node rightNode = findNode(root.getRChild(), x); if (null != rightNode) { return rightNode; } return null; } //返回某节点的父节点 public Node getParent(Node root, int x) { if (root == null) { return null; } Node childL = root.getLChild(); Node childR = root.getRChild(); if (childL != null && childL.getData() == x) { return root; } if (childR != null && childR.getData() == x) { return root; } Node parentL = getParent(root.getLChild(), x); if (parentL != null) { return parentL; } Node parentR = getParent(root.getRChild(), x); if (parentR != null) { return parentR; } return null; } }
其中对二叉树的遍历