14
06/2015
[LeetCode] Invert Binary Tree
Invert Binary Tree
Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1Trivia:
This problem was inspired by this original tweet by Max Howell:
解题思路:
用递归解即可。先将以左孩子节点为根节点的子树翻转,然后将以右孩子节点为根节点的子树翻转,然后交换一下根节点的左右子树。
/** * 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){ TreeNode* leftNode = invertTree(root->left); TreeNode* rightNode = invertTree(root->right); root->right = leftNode; root->left = rightNode; } return root; } };
转载请注明:康瑞部落 » [LeetCode] Invert Binary Tree
0 条评论