翻转一棵二叉树。
示例:
输入:
4
/
2 7
/ /
1 3 6 9
输出:
4
/
7 2
/ /
9 6 3 1
python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
stack =[root]
while stack:
node=stack.pop(0)
node.left,node.right=node.right,node.left
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root
c++
/** * 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 root; auto q=queue<TreeNode*>(); q.push(root); while(!q.empty()){ auto n=q.front();q.pop(); swap(n->left,n->right); if(n->left!=nullptr){ q.push(n->left); } if(n->right!=nullptr){ q.push(n->right); } } return root; } };