leetcode 226--Invert Binary Tree

来源:互联网 发布:知商金融排名 编辑:程序博客网 时间:2024/04/28 16:35

Invert Binary Tree

My Submissions
Total Accepted: 41269 Total Submissions: 103940 Difficulty: Easy

Invert a binary tree.

     4   /   \  2     7 / \   / \1   3 6   9
to
     4   /   \  7     2 / \   / \9   6 3   1

解题思路:

利用递归思想,由底向上进行翻转,当需要翻转的树的根节点为空时返回

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* invertTree(struct TreeNode* root) {
    
    if (root == NULL) {
        return NULL;
    } else {
        invertree(root);
        return root;
    }
    
}
    void invertree(struct TreeNode* root) {
        if(root == NULL)
        return;
        invertree(root->left);
        invertree(root->right);
        struct TreeNode* q;
        q=root->left;
        root->left=root->right;
        root->right=q;
        
    }

0 0
原创粉丝点击