【C++】翻轉二叉樹(遞迴、非遞迴)

wshidaboss發表於2024-03-06
//使用遞迴翻轉二叉樹
TreeNode* reverseTree(TreeNode* root) {
  if (!root) return root;
  swap(root->left, root->right);
  reverseTree(root->left);
  reverseTree(root->right);
  return root;
}
//使用佇列翻轉二叉樹 層序遍歷
TreeNode* invertTree(TreeNode* root) {
  queue<TreeNode*> q;
  if (!root) return root;
  q.push(root);
  while (!q.empty()) {
    TreeNode* node;
    for (int i = 0; i < q.size(); ++i) {
      node = q.front();
      q.pop();
      if (node->left && node->right) {
        swap(node->left, node->right);
      }
      if (node->left) q.push(node->left);
      if (node->right) q.push(node->right);
    }
  }
  return root;
}

相關文章