二叉树基本操作C++

#include <cstdio>
#include <climits>
#include <cassert>
#include <iostream>
#include <algorithm>
#include <string>

struct Node {
  int value = 0;
  struct Node *left = nullptr;
  struct Node *right = nullptr;
};

void preorder_print_aux(Node *T) {
  if (T == nullptr) {
    return ;
  }
  std::cout << T->value << ' ';
  preorder_print_aux(T->left);
  preorder_print_aux(T->right);
}

void preorder_print(Node *T) {
  preorder_print_aux(T);
  std::cout << std::endl;
}

Node *CreateBiTreeAux(Node *&T, std::vector<int>::const_iterator &ite) {
  // 按先序次序输入二叉树中结点的值(一个字符),空格字符表示空树,
  // 构造二叉链表表示的二叉树T。
  int elem = *ite++;

  if (elem == INT_MIN) {
    T = nullptr;
  } else {
    T = new Node;
    T->value = elem;              // 生成根结点
    CreateBiTreeAux(T->left, ite);   // 构造左子树
    CreateBiTreeAux(T->right, ite);   // 构造右子树
  }
  return T;
}

Node *create_tree(Node *&T, const std::vector<int> &input) {
  std::vector<int>::const_iterator ite = input.begin();
  CreateBiTreeAux(T, ite);

  return T;
}

void free(Node *&T)
{
  if (T == nullptr)
    return;

  free(T->left);
  free(T->right);
  delete T;
  T = nullptr;
}

int sum(struct Node *tree, int *max_sum) {
  if (tree->left == nullptr && tree->right == nullptr) {
    *max_sum = tree->value;
    return tree->value;
  }

  int left_sum = INT_MIN;
  int l_max_sum = INT_MIN;
  if (nullptr != tree->left) {
    left_sum = sum(tree->left, &l_max_sum);
  }

  int right_sum = INT_MIN;
  int r_max_sum = INT_MIN;
  if (nullptr != tree->right) {
    right_sum = sum(tree->right, &r_max_sum);
  }

  int ret = tree->value + left_sum + right_sum;
  if (ret < l_max_sum) {
    ret = l_max_sum;
  }
  if (ret < r_max_sum) {
    ret = r_max_sum;
  }

  *max_sum = ret;
  return ret;
}

void assert_equal(int expect, std::vector<int> tree) {
  Node *T = nullptr;
  create_tree(T, tree);
  preorder_print(T);
  int ret = 0;
  sum(T, &ret);
  if (expect != ret) {
    fprintf(stderr, "Expect %d, but result is %d.\n", expect, ret);
    exit(1);
  }
  free(T);
}

int main() {
  assert_equal(3, {3, INT_MIN, INT_MIN});
  assert_equal(6, {1, 2, INT_MIN, INT_MIN, 3, INT_MIN, INT_MIN});
  assert_equal(2, {5, -8, INT_MIN, INT_MIN, 2, INT_MIN, INT_MIN});
  assert_equal(14, {-5, 10, -6, INT_MIN, INT_MIN, 5, INT_MIN, INT_MIN, 10, INT_MIN, INT_MIN});
  assert_equal(1, {-5, -10, -6, INT_MIN, INT_MIN, 1, INT_MIN, INT_MIN, -10, INT_MIN, INT_MIN});

  std::cout << "OK\n";

  return 0;
}

 

posted on 2016-09-07 22:15  jjtx  阅读(511)  评论(0编辑  收藏  举报

导航