leetcode刷题日记——Invert Binary Tree

来源:互联网 发布:上师大网络课程 编辑:程序博客网 时间:2024/05/18 02:44
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; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode* invertTree(TreeNode* root) {         if(root==NULL) return NULL;         else if(root->left==NULL&&root->right==NULL) return root;         else{             TreeNode *temp=NULL;             temp=root->left;             root->left=root->right;             root->right=temp;             invertTree(root->left);             invertTree(root->right);             return root;         }    }};


0 0
原创粉丝点击