《leetCode》:Invert Binary Tree

题目

Invert a binary tree.

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

思路

此题比较简单,在《剑指Offer》上面做过。

具体思路就是:如果某节点存在子节点,则左右子节点交换即可,然后依次递推即可。

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

你可能感兴趣的:(LeetCode,tree,binary,invert)