1. 程式人生 > >翻轉二叉樹(遞迴與非遞迴)

翻轉二叉樹(遞迴與非遞迴)

翻轉一棵二叉樹

樣例

  1         1
 / \       / \
2   3  => 3   2
   /       \
  4         4

遞迴版本

先翻轉左子樹,後翻轉右子樹,然後對整個樹進行翻轉

void swapTree(TreeNode *&root){
    TreeNode *tmp = root->left;
    root->left = root->right;
    root->right = tmp;
}

void invertBinaryTree(TreeNode *root) {
    // write your code here
    if(root == NULL)
        return;

    invertBinaryTree(root->left);
    invertBinaryTree(root->right);

    swapTree(root);
}

非遞迴版本

非遞迴版本用棧來實現,到訪問到頭節點的時候,將其左子樹和右子樹互換即可。

void swapTree(TreeNode *&root){
    TreeNode *tmp = root->left;
    root->left = root->right;
    root->right = tmp;
}
void invertBinaryTree(TreeNode *root) {
    // write your code here
    if(root == NULL)
        return;
    stack<TreeNode*> stk;
    stk.push(root);
    while(!stk.empty())
    {
        TreeNode *tmp = stk.top();
        stk.pop();
        swapTree(tmp);
        if(tmp->left)
            stk.push(tmp->left);
        if(tmp->right)
            stk.push(tmp->right);
    }
}