[leetcode]:Invert a binary tree.

来源:互联网 发布:好看的字体软件 编辑:程序博客网 时间:2024/05/21 15:02

1.题目

翻转一棵二叉树
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1

2.分析

遍历树,交换左右节点。可以手动遍历或递归

3.代码

TreeNode* invertTree(TreeNode* root) {    if (root == NULL)        return root;    TreeNode* tempL= invertTree(root->right);    TreeNode* tempR = invertTree(root->left);    root->left = tempL;    root->right = tempR;    return root;}
原创粉丝点击