Binary Tree

 
  1. /**
  2.  * filename: BinaryTree.java
  3.  * package:
  4.  * author: Nick Ma
  5.  * email: nick.ma85@yahoo.com
  6.  * date: Nov 1, 2008
  7.  * description: this class implements a binary tree data structure.
  8.  */
  9. public   class  BinaryTree {
  10.          // Data Field
  11.         
  12.          /** the root of the binary tree */
  13.          protected  TreeNode root;
  14.          /**
  15.          * description: default constructor
  16.          */
  17.          public  BinaryTree() {
  18.                  // TODO Auto-generated constructor stub
  19.                  this .root =  null ;
  20.         }
  21.         
  22.          /**
  23.          * description: protected constructor just to build a new binary tree 
  24.          * with only root node
  25.          */
  26.          protected  BinaryTree(TreeNode node) {
  27.                  this .root = node;
  28.         }
  29.          /**
  30.          * description: the constructor to build a new binary tree
  31.          * @param data - the info stored in the root node
  32.          * @param leftTree - the left subtree of the root
  33.          * @param rightTree - the right subtree of the root
  34.          */
  35.          public  BinaryTree(Object data, BinaryTree leftTree, BinaryTree rightTree) {
  36.                  // store the data to the root node
  37.                 root.setData(data);
  38.                 
  39.                  // set the left subtree of the root
  40.                  if (leftTree !=  null ) {
  41.                         root.setLeft(leftTree.root);
  42.                 }  else  {
  43.                         root.setLeft( null );
  44.                 }
  45.                 
  46.                  // set the right subtree of the root
  47.                  if (rightTree !=  null ) {
  48.                         root.setRight(rightTree.root);
  49.                 }  else  {
  50.                         root.setRight( null );
  51.                 }
  52.         }
  53.         
  54.          /**
  55.          * description: return the left subtree of the root
  56.          * @return - the left subtree
  57.          */
  58.          public  BinaryTree getLeftSubTree() {
  59.                  if (root !=  null  && root.getLeft() !=  null ) {
  60.                          return   new  BinaryTree(root.getLeft());
  61.                 }  else  {
  62.                          return   null ;
  63.                 }
  64.         }
  65.         
  66.          /**
  67.          * description: return the right subtree of the root
  68.          * @return - the right subtree
  69.          */
  70.          public  BinaryTree getRightSubTree() {
  71.                  if (root !=  null  && root.getRight() !=  null ) {
  72.                          return   new  BinaryTree(root.getRight());
  73.                 }  else  {
  74.                          return   null ;
  75.                 }
  76.         }
  77.         
  78.          /**
  79.          * description: determine whether the root has no children or not
  80.          * @return - true if the root has no children
  81.          */
  82.          public   boolean  isLeaf() {
  83.                  return  (root !=  null  && root.getLeft() ==  null  && root.getRight() ==  null );
  84.         }
  85.         
  86.          /**
  87.          * description: perform a pre-order traversal
  88.          * @param node - the local root
  89.          */
  90.          public   void  preOrderTraverse(TreeNode node) {       
  91.                  if (node ==  null ) {
  92.                          // do something when node is null
  93.                 }  else  {
  94.                          // do something to root node
  95.                          // then traverse to its children
  96.                         preOrderTraverse(node.getLeft());
  97.                         preOrderTraverse(node.getRight());
  98.                 }
  99.         }
  100.         
  101.          /**
  102.          * description: perform a in-order traversal
  103.          * @param node - the local root
  104.          */
  105.          public   void  inOrderTraverse(TreeNode node) {
  106.                  if (node ==  null ) {
  107.                          // do something when node is null
  108.                 }  else  {
  109.                         inOrderTraverse(node.getLeft());
  110.                          // do something to root node
  111.                          // then traverse to its children
  112.                         inOrderTraverse(node.getRight());
  113.                 }
  114.         }
  115.         
  116.          /**
  117.          * description: perform a post-order traversal
  118.          * @param node - the local root
  119.          */
  120.          public   void  postOrderTraverse(TreeNode node) {
  121.                  if (node ==  null ) {
  122.                          // do something when node is null
  123.                 }  else  {
  124.                         postOrderTraverse(node.getLeft());
  125.                         postOrderTraverse(node.getRight());
  126.                          // do something to root node
  127.                          // then traverse to its children
  128.                 }
  129.         }
  130.         
  131.          /**
  132.          * description: get the depth of this expression tree
  133.          * @param node - the local root node
  134.          * @return - the depth of the local root
  135.          */
  136.          protected   int  getDepth(TreeNode node) {
  137.                  if (node ==  null ) {
  138.                          return   0 ;
  139.                 }  else  {
  140.                          return   1  + Math.max(getDepth(node.getLeft()), getDepth(node.getRight()));
  141.                 }
  142.         }
  143. }

  1. /**
  2.  * filename: TreeNode.java
  3.  * package: 
  4.  * author: Nick Ma
  5.  * email: nick.ma85@yahoo.com
  6.  * date: Nov 1, 2008
  7.  * description: this class encapsulates a tree node.
  8.  */
  9. public   class  TreeNode {
  10.          // Data Field
  11.         
  12.          /** info stored in this root node */
  13.          private  Object data;
  14.         
  15.          /** reference to the left child */
  16.          private  TreeNode left;
  17.         
  18.          /** reference to the right child */
  19.          private  TreeNode right;
  20.          /**
  21.          * description: default constructor
  22.          */
  23.          public  TreeNode() {
  24.                  // TODO Auto-generated constructor stub
  25.                 data =  null ;
  26.                 left =  null ;
  27.                 right =  null ;
  28.         }
  29.          /**
  30.          * description: constructor to initialize its data with no left and right children
  31.          * @param data - the data to store in this node
  32.          */
  33.          public  TreeNode(Object data) {
  34.                  this .data = data;
  35.                  this .left =  null ;
  36.                  this .right =  null ;
  37.         }
  38.         
  39.          /**
  40.          * description: constructor with fields
  41.          * @param data - the data to store in this node
  42.          * @param left - the left child
  43.          * @param right - the right child
  44.          */
  45.          public  TreeNode(Object data, TreeNode left, TreeNode right) {
  46.                  this .data = data;
  47.                  this .left = left;
  48.                  this .right = right;
  49.         }
  50.          /* (non-Javadoc)
  51.          * @see java.lang.Object#toString()
  52.          */
  53.          @Override
  54.          public  String toString() {
  55.                  // TODO Auto-generated method stub
  56.                  return   this .data.toString();
  57.         }
  58.          /**
  59.          * @return the data
  60.          */
  61.          public  Object getData() {
  62.                  return  data;
  63.         }
  64.          /**
  65.          * @param data the data to set
  66.          */
  67.          public   void  setData(Object data) {
  68.                  this .data = data;
  69.         }
  70.          /**
  71.          * @return the left
  72.          */
  73.          public  TreeNode getLeft() {
  74.                  return  left;
  75.         }
  76.          /**
  77.          * @param left the left to set
  78.          */
  79.          public   void  setLeft(TreeNode left) {
  80.                  this .left = left;
  81.         }
  82.          /**
  83.          * @return the right
  84.          */
  85.          public  TreeNode getRight() {
  86.                  return  right;
  87.         }
  88.          /**
  89.          * @param right the right to set
  90.          */
  91.          public   void  setRight(TreeNode right) {
  92.                  this .right = right;
  93.         }
  94. }

<think>我们被要求详细介绍二叉树(binary tree)。结合用户提供的引用内容,我们可以从以下几个方面展开: 1. 二叉树的定义和基本概念(包括节点、根、子树等) 2. 二叉树的性质(如第i层最多有2^(i-1)个节点,深度为k的二叉树最多有2^k-1个节点等) 3. 特殊类型的二叉树(满二叉树、完全二叉树、完美二叉树等,注意引用[3]中提到的术语区别) 4. 二叉树的存储结构(通常用链式存储,如引用[1][2][4]中的节点结构) 5. 二叉树的遍历(深度优先:前序、中序、后序;广度优先:层次遍历) 6. 二叉树的构建(如引用[1]中的手动构建和引用[4]中的插入构建) 7. 二叉树的应用 由于用户要求详细,我们将每个部分都进行适当的展开。 注意:用户提供的引用中,引用[3]提到了满二叉树和完全二叉树的区别,并引入了完美二叉树的概念,我们需要明确这些术语。 下面开始组织内容: </think>### 二叉树(Binary Tree)详解 二叉树是一种重要的非线性数据结构,其特点是每个节点最多有两个子节点:**左子节点**和**右子节点**。这种结构天然支持递归定义,在算法设计和数据处理中具有广泛应用。 --- #### 一、二叉树核心概念 1. **节点结构** 每个节点包含三个部分: ```java class TreeNode { int data; // 节点存储的数据 TreeNode left; // 左子节点指针 TreeNode right; // 右子节点指针 } ``` 引用示例代码:[^4] 2. **基本术语** - **根节点(Root)**:树的起始节点(如`tree.root`)[^1] - **叶子节点(Leaf)**:左右子节点均为空的节点 - **深度(Depth)**:从根节点到当前节点的路径长度 - **高度(Height)**:从当前节点到最深叶子节点的路径长度 - **度(Degree)**:节点的子节点数量(二叉树中最大为2) 3. **特殊二叉树类型** | 类型 | 定义 | 示例 | |------|------|------| | **满二叉树(Full Binary Tree)** | 每个节点有0或2个子节点 | `A(B,C)` | | **完全二叉树(Complete Binary Tree)** | 除最后一层外全满,最后一层从左向右填充 | `A(B(D,E),C(F))` | | **完美二叉树(Perfect Binary Tree)** | 所有叶子节点在同一层,且每层都被填满 | `A(B(D,E),C(F,G))` [^3] | --- #### 二、二叉树存储结构 1. **链式存储(主流方式)** - 节点通过指针链接(如上文Java代码实现)[^4] - 优点:动态内存分配,插入删除灵活 - 缺点:指针占用额外空间 2. **顺序存储(数组实现)** - 根节点索引:`i=0` - 左子节点索引:`2i+1` - 右子节点索引:`2i+2` - 适用场景:完全二叉树存储优化 --- #### 三、二叉树遍历算法 1. **深度优先遍历(DFS)** ```java // 前序遍历:根 → 左 → 右 void preOrder(TreeNode node) { if (node == null) return; System.out.print(node.data + " "); // 访问根 preOrder(node.left); // 遍历左子树 preOrder(node.right); // 遍历右子树 } ``` - **中序遍历**:左 → 根 → 右(二叉搜索树可输出有序序列)[^1] - **后序遍历**:左 → 右 → 根(常用于表达式树求值) 2. **广度优先遍历(BFS)** 使用队列实现层次遍历: ```java void levelOrder(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); System.out.print(node.data + " "); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } } ``` --- #### 四、二叉树构建方法 1. **手动构建(静态)** 直接连接节点(适用于固定结构): ```java BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); // 引用[1]示例 ``` 2. **插入构建(动态)** 根据规则递归插入(如二叉搜索树): ```java void insert(TreeNode node) { if (root == null) root = node; else if (node.data < current.data) current.left = insert(current.left, node); else current.right = insert(current.right, node); } // 引用[4]逻辑简化版 ``` --- #### 五、二叉树关键性质 1. **节点数量关系** - 第 $i$ 层最多有 $2^{i-1}$ 个节点 - 深度为 $k$ 的树最多有 $2^k - 1$ 个节点 2. **高度与节点关系** 对于 $n$ 个节点的二叉树: - 最小高度:$\lfloor \log_2n \rfloor + 1$ - 最大高度:$n$(退化为链表) 3. **特殊性质** 在二叉搜索树中(BST): - 左子树所有节点值 $<$ 根节点值 - 右子树所有节点值 $>$ 根节点值 --- #### 六、二叉树应用场景 1. **数据检索**:二叉搜索树实现$O(\log n)$查找 2. **表达式解析**:算术表达式的语法树表示 3. **文件系统**:目录树结构建模 4. **游戏AI**:决策树实现行为选择 5. **压缩算法**:哈夫曼编码构建最优前缀树 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值