二叉树两个结点的最低共同父结点

需要思考为什么采用Inorder遍历是可以的?其他遍历方式结果不正确?

#include <stdio.h>
template<typename T>
class TreeNode {
 public:
  TreeNode() :left_(NULL), right_(NULL) {}
  T value_;
  TreeNode* left_;
  TreeNode* right_;
};
template<typename T>
class VisitContext {
 public:
  VisitContext(TreeNode<T>* node1, TreeNode<T>* node2)
      : node1_(node1), node2_(node2), node1_found_(false), node2_found_(false), depth_(0), min_depth_(0x7FFFFFFF), same_parent_(NULL) {
  }
  TreeNode<T>* node1_;
  TreeNode<T>* node2_;
  bool node1_found_;
  bool node2_found_;
  int depth_;
  int min_depth_;
  TreeNode<T>* same_parent_;
};
template<typename T>
void SameParent(TreeNode<T>* current, VisitContext<T>* context) {
  if (current) {
    (context->depth_)++;
    SameParent(current->left_, context);
    if (current == context->node1_) {
      context->node1_found_ = true;
      if (!context->node2_found_) {
        context->min_depth_ = context->depth_;
        context->same_parent_ = current;
      }
    }
    if (current == context->node2_) {
      context->node2_found_ = true;
      if (!context->node1_found_) {
        context->min_depth_ = context->depth_;
        context->same_parent_ = current;
      }
    }
    if (context->node1_found_ || context->node2_found_) {
      if (context->min_depth_ > context->depth_ &&
          !(context->node1_found_ && context->node2_found_)) {
        context->min_depth_ = context->depth_;
        context->same_parent_ = current;
        printf("min_depth:%d\n", context->min_depth_);
      }
    }

    SameParent(current->right_, context);
    (context->depth_)--;

  }
}
int main(int argc, char** argv) {
  size_t kNodeAmount = 15;
  TreeNode<int> tree_nodes[kNodeAmount];
  for (int i = 0; i < kNodeAmount; ++i) {
    tree_nodes[i].value_ = i;
  }
  int i = 0;
  int left_child = 0;
  int right_child = 0;
  while (true) {
    left_child = 2 * (i + 1) - 1;
    right_child = 2 * (i + 1);
    if (left_child >= kNodeAmount || right_child >= kNodeAmount) {
      break;
    }
    tree_nodes[i].left_ = tree_nodes + left_child;
    tree_nodes[i].right_ = tree_nodes + right_child;
    i++;
  }
  int depth = 0;
  VisitContext<int> visit_context(tree_nodes + 4, tree_nodes + 3);
  SameParent(tree_nodes, &visit_context);
  if (visit_context.same_parent_ != NULL) {
    printf("%d", visit_context.same_parent_->value_);
  }
}
    

程序采用VisitContext来记录访问的轨迹和遍历的结果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值