//使用递归翻转二叉树
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;
}

 

posted on 2024-03-06 11:30  wshidaboss  阅读(39)  评论(0编辑  收藏  举报