翻转二叉树

来源:互联网 发布:哪类商品禁止在淘宝网 编辑:程序博客网 时间:2024/06/08 04:29

描述:翻转一棵二叉树

样例:

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

解题思路:翻转一棵二叉树,就是将根节点的左右指针指向的值进行互换。所以脑子里最先想到的是sawp函数,然后想着用递归的方法来实现。

实现代码:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    void invertBinaryTree(TreeNode *root) {
        // write your code here
         if(root!=NULL)
         {
             invertBinaryTree(root->left);
             invertBinaryTree(root->right);
             swap(root->left,root->right);
         }
    }
};

做题感想:刚开始的时候,我把swap函数放在了前面,结果一直是Runtime Error。后来才发现应该先交换它的左子树与右子树,不然就会乱套了。

0 0