二叉树的镜像
思想:
先判断是否为空节点;
将左右子树交换,然后调用迭代函数,将左右子树的节点当做根节点再输入迭代函数
最后返回这个树的根节点。
python
1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 class Solution: 8 # 返回镜像树的根节点 9 def Mirror(self, root): 10 # write code here 11 if not root: 12 return root; 13 root.left,root.right = root.right,root.left 14 self.Mirror(root.left) 15 self.Mirror(root.right) 16 return root
c++
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Solution { public: void Mirror(TreeNode *pRoot) { if(!pRoot) return; swap(pRoot->left,pRoot->right); Mirror(pRoot->left); Mirror(pRoot->right); } };