完全二叉树插入
2015-09-26 00:03
316 查看
题目:给一颗完全二叉树,要求插入一个节点后,依然是完全二叉树。
分析:利用完全二叉树的性质,找到要插入的位置,先判断左子树的最右结点与右子树的最左结点高度,如果相等,只需要插入到左子树即可,否则插入右子树。
实现:
分析:利用完全二叉树的性质,找到要插入的位置,先判断左子树的最右结点与右子树的最左结点高度,如果相等,只需要插入到左子树即可,否则插入右子树。
实现:
/**题目:给完全二叉树插入一个节点,插完后保证还是完全二叉树 * @author ShaoCheng * @version 1.0 2015-9-24 */ class TreeNode{ int val; TreeNode left, right; TreeNode(int key){ val = key; } } public class Main { public static void main(String[] args){ TreeNode p1 = new TreeNode(1); TreeNode p2 = new TreeNode(2); TreeNode p3 = new TreeNode(3); TreeNode p4 = new TreeNode(4); p1.left = p2; p1.right = p3; p2.left = p4; TreeNode node = new TreeNode(100); TreeNode root = insertBinary(p1, node); printTree(root); } //中序遍历 public static void printTree(TreeNode root){ if(root == null) return; System.out.println(root.val); printTree(root.left); printTree(root.right); } public static TreeNode insertBinary(TreeNode root, TreeNode node){ if(root == null) return node; else if(node == null) return root; if(root.left == null){ root.left = node; return root; } else if(root.right == null){ root.right = node; return root; } int lrh = 0; int rrh = 0; TreeNode pNode = root.left; while(pNode != null){ lrh++; pNode = pNode.right; } pNode = root.right; while(pNode != null){ rrh++; pNode = pNode.left; } if(lrh != rrh){ insertBinary(root.right, node); } else insertBinary(root.left, node); return root; } }
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- C语言二叉树的非递归遍历实例分析
- 使用C语言构建基本的二叉树数据结构
- C++非递归队列实现二叉树的广度优先遍历
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- C#非递归先序遍历二叉树实例
- C++非递归建立二叉树实例
- C语言实现找出二叉树中某个值的所有路径的方法
- C++实现二叉树遍历序列的求解方法
- C语言实现二叉树遍历的迭代算法
- 用C语言判断一个二叉树是否为另一个的子结构
- C++实现二叉树非递归遍历方法实例总结
- C++二叉树结构的建立与基本操作
- 深入遍历二叉树的各种操作详解(非递归遍历)
- JavaScript数据结构和算法之二叉树详解
- java使用归并删除法删除二叉树中节点的方法
- Java中二叉树数据结构的实现示例
- python数据结构之二叉树的建立实例
- python数据结构树和二叉树简介
- python数据结构之二叉树的统计与转换实例