设一棵二叉树结点的存储结构为 (L child,date,R child),p为根结点

试设计一遍历算法,求出左子树或右子树的data值为x的结点,要求将求出结点的data值存入S数组

望采纳

下列代码实现使用递归的遍历算法,可以求出左子树或右子树的结点的 data 值为 x 的结点,并将求出结点的 data 值存入 S 数组:

struct TreeNode {
  int data;
  TreeNode *left;
  TreeNode *right;
};

void findNode(TreeNode *p, int x, int &i, int S[]) {
  if (p != NULL) {
    // 先搜索左子树
    findNode(p->left, x, i, S);

    // 再搜索右子树
    findNode(p->right, x, i, S);

    // 搜索当前结点
    if (p->data == x) {
      S[i] = p->data;
      i++;
    }
  }
}