数据结构二叉树的两个题目

本文介绍了二叉树的两种核心算法:一是通过非递归方式判断二叉树是否为二叉排序树;二是通过递归方式查找二叉排序树中与指定值最接近的较小值和较大值。文章提供了具体的类C语言实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,设二叉树以二叉链表形式存放,用类C语言设计非递归算法判断一棵根结点为T的二叉树是否为 二叉排序树

   (思路:从根结点开始访问,每次从栈中取出一个节点,将其子结点加入到栈中)

    这里先给出递归的解法:

int IsSearchTree(const BTNode *t){
  if(!t)        //空二叉树情况
   return 1;
  else if(!(t->lchild) && !(t->rchild))//左右子树都无情况
      return 1;
  else if((t->lchild) && !(t->rchild)){//只有左子树情况
      if(t->lchild->data>t->data)
    return 0;
   else
    return IsSearchTree(t->lchild);
  }
  else if((t->rchild) && !(t->lchild)){//只有右子树情况
      if(t->rchild->data<t->data)
    return 0;
   else
    return IsSearchTree(t->rchild);
  }
  else{                                //左右子树全有情况
   if((t->lchild->data>t->data) ||(t->rchild->data<t->data))
    return 0;
   else
    return IsSearchTree(t->lchild) && IsSearchTree(t->rchild);
  }
}

2,设二叉排序树以二叉链表形式存放,用类C语言设计递归算法求一棵根结点为T的二叉树上小于k且最靠近k的数据元素a和大于k且最靠近k数据元素b

实现下列函数:
void OutX(BiTree t, KeyType x, KeyType &a, KeyType &b);
/* a: Return the nearest and smaller value to x, */
/* but return MINV if no the value in t. */
/* b: Return the nearest and larger value to x. */
/* but return MAXV if no the value in t. */

二叉树的类型BiTree定义如下:
typedef struct {
   KeyType key;
     ... ... // 其他数据域
} ElemType;
typedef struct BiTNode {
   ElemType data;
   BiTNode *lchild,*rchild;
}BiTNode, *BiTree;

代码如下:

void Out(BiTree t, KeyType x, KeyType &a, KeyType &b)
{  if( t )
   if( x == t->data.key )
{Out( t -> lchild, x, a, b ); Out( t -> rchild, x, a, b );}
   else if( x < t->data.key )
{b = t -> data.key;Out( t -> lchild, x, a, b );}
  else
{a = t -> data.key; Out( t -> rchild, x, a, b );}
     }
   
void OutX(BiTree t, KeyType x, KeyType &a, KeyType &b)
/* a: Return the nearest and smaller value to x, */
/*    but return MINV if no the value in t.      */
/* b: Return the nearest and larger  value to x. */
/*    but return MAXV if no the value in t.      */
{
   a = '<'; b = '>';
   Out( t, x, a, b ); 
}

### 数据结构二叉树练习题 #### 题目一:构建并遍历二叉树 给定一棵二叉树的前序遍历和中序遍历序列,可以唯一确定这棵二叉树。通过这两个序列重建二叉树,并输出其后序遍历和按层次遍历的结果。 对于这个问题,可以通过以下方法解决: 1. 前序遍历的第一个节点总是根节点。 2. 使用这个根节点可以在中序遍历中找到根的位置,从而划分出左子树和右子树。 3. 对于每一个子树重复上述过程直到完成整棵树的构造。 ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def build_tree(preorder, inorder): if not preorder or not inorder: return None root_val = preorder[0] root_index_inorder = inorder.index(root_val) root = TreeNode(root_val) root.left = build_tree( preorder[1:1 + root_index_inorder], inorder[:root_index_inorder] ) root.right = build_tree( preorder[root_index_inorder + 1:], inorder[root_index_inorder + 1:] ) return root def post_order_traversal(node): result = [] if node is not None: result += post_order_traversal(node.left) result += post_order_traversal(node.right) result.append(node.val) return result def level_order_traversal(node): from collections import deque levels = [] queue = deque([node]) while queue: current_node = queue.popleft() if current_node: levels.append(current_node.val) if current_node.left: queue.append(current_node.left) if current_node.right: queue.append(current_node.right) return levels ``` 以上代码实现了基于前序和中序遍历创建二叉树的功能,并提供了两种不同的遍历方式来验证所建树是否正确[^1]。 #### 查找特定节点及其路径 为了实现这一功能,可以从根节点开始递归地向下搜索目标字符所在的节点位置。每当访问一个新的节点时记录下当前路径;一旦找到了匹配的目标就停止继续探索其他分支并将已保存下来的路径作为结果返回。 ```python def find_path_to_node(root, target_char, path=[]): if root and root.val == target_char: return True elif root: found_left = False found_right = False new_path = path.copy() + [root.val] if root.left: found_left = find_path_to_node(root.left, target_char, new_path) if root.right and not found_left: found_right = find_path_to_node(root.right, target_char, new_path) if found_left or found_right: path.extend(new_path[len(path):]) return True return False ``` 这段函数接受三个参数:`root`(要查询的二叉树), `target_char`(想要寻找的大写英文字母), 和一个可选列表用于存储到达目的节点经过的所有节点值组成的路径.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值