Recursion 二叉树的摆动
问题如前所述,我的解决方案如下:返回BST树在一个方向上的摆动量。 摆动由以下节点的数量表示: “不平衡”-只有一侧为空,左侧为空 摇摆树返回其摇摆的负值 任何右摆偏移左摆,反之亦然Recursion 二叉树的摆动,recursion,tree,binary-tree,Recursion,Tree,Binary Tree,问题如前所述,我的解决方案如下:返回BST树在一个方向上的摆动量。 摆动由以下节点的数量表示: “不平衡”-只有一侧为空,左侧为空 摇摆树返回其摇摆的负值 任何右摆偏移左摆,反之亦然 int tree_sway(Node * node){ if(!node){ return 0; } int m = tree_sway(node->right) + 1; int n = tree_sway(node->left) - 1; return
int tree_sway(Node * node){
if(!node){
return 0;
}
int m = tree_sway(node->right) + 1;
int n = tree_sway(node->left) - 1;
return m - n;
}
对于树摇摆问题,我发布的解决方案正确吗?如果不是,那么解决这个问题的唯一方法是创建一个helper函数来跟踪递归步骤的左转和右转次数吗?您发布的代码不太正确。例如,在具有根和叶的树上,无论叶位于哪一侧,结果始终为0。一种方法是:
int tree_swap(Node *node) {
# base case of the recursion
if (!node) { return 0; }
# go down the left and right branches and add their scores
int score = tree_swap(node->left) + tree_swap(node->right);
# adjust the score for the missing children of the current node
if (!node->left) { score++; }
if (!node->right) { score--; }
return score;
}
一般的想法是,当你递归时,你首先沿着树一直往下走,然后当你返回时,你计算缺少的左分支和右分支,并将运行的汇总结果传递给树。你发布的代码不太正确。例如,在具有根和叶的树上,无论叶位于哪一侧,结果始终为0。一种方法是:
int tree_swap(Node *node) {
# base case of the recursion
if (!node) { return 0; }
# go down the left and right branches and add their scores
int score = tree_swap(node->left) + tree_swap(node->right);
# adjust the score for the missing children of the current node
if (!node->left) { score++; }
if (!node->right) { score--; }
return score;
}
一般的想法是,当你递归的时候,你首先沿着树往下走,然后当你回来的时候,你数一数缺失的左、右分支,然后把运行的结果传递给树