需要思考为什么采用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来记录访问的轨迹和遍历的结果。