题目:

翻转一棵二叉树

样例:

clipboard.png

思路:

采用递归的想法:
交换根节点的左右子树。
对左右子树分别执行递归反转 。

参考答案:

/**
 * 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)    return;//注意return NULL不行
        
        TreeNode *temp = root->left;
        root->left = root->right;
        root->right = temp;
        
        invertBinaryTree(root->left);
        invertBinaryTree(root->right);
    }
};

wydong
40 声望5 粉丝

wyd