生成一个满二叉数算法
1、树结构类
public class TreeNode<T> { T val; TreeNode<T> parent; TreeNode<T> right; TreeNode<T> left; public TreeNode(){ } public TreeNode(T val){ this.val = val; this.parent = null; this.right = null; this.left = null; } public TreeNode(T val, TreeNode<T> parent, TreeNode<T> right, TreeNode<T> left) { this.val = val; this.parent = parent; this.right = right; this.left = left; } public T getVal() { return val; } public void setVal(T val) { this.val = val; } public TreeNode<T> getParent() { return parent; } public void setParent(TreeNode<T> parent) { this.parent = parent; } public TreeNode<T> getRight() { return right; } public void setRight(TreeNode<T> right) { this.right = right; } public TreeNode<T> getLeft() { return left; } public void setLeft(TreeNode<T> left) { this.left = left; } }
二、获取满二叉数的算法
public class Struggle { public static void main(String[] args) { /**创建满二叉树的层级数*/ int total = 6; /** 获取难二叉数*/ TreeNode tree = getTree(total); } /** 创建根节点*/ public static TreeNode getTree(int total) { /** 如果获取的层级数小于0,直接返回null*/ if (total <= 0) { return null; } /** 创建根节点 */ TreeNode root = new TreeNode(1); /** 维护剩余节点*/ getTreeNode(root, 1, total); return root; } /** * 递归获取满二叉数 * @param parent 根节点 * @param count 当前层数 * @param total 总层数 */ public static void getTreeNode(TreeNode parent, int count, int total) { /** 当前层与创建的层一致,直接返回*/ if (count == total) { return; } /** 维护左右节点*/ parent.setLeft( new TreeNode(1, parent,null, null)); parent.setRight( new TreeNode(1, parent,null, null)); /**当前层递增*/ count++; /** 维护左右节点的左右节点*/ getTreeNode(parent.getLeft(), count, total); getTreeNode(parent.getRight(), count, total); } }
缘于生活,而归于工作。本人所书,而意于分享。
如有转载,请注明出处!
--活出自己范儿