【leetcode每日一题】226.Invert Binary Tree
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:
void invert(TreeNode* root)
{
if(root==NULL)
return;
else
{
TreeNode* left=root->left;
root->left=root->right;
root->right=left;
invert(root->left);
invert(root->right);
}
}
TreeNode* invertTree(TreeNode* root) {
if(root==NULL)
return root;
invert(root);
return root;
}
};
还没有评论,来说两句吧...