[Leetcode] Invert Binary Tree

来源:互联网 发布:北京美工培训 便宜 编辑:程序博客网 时间:2024/06/06 07:22

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)        return NULL;        root->left = invertTree(root->left);    root->right = invertTree(root->right);            struct TreeNode *tmp = root->left;    root->left = root->right;    root->right = tmp;    return root;}







0 0