56.翻转二叉树
递归
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return root;
}
TreeNode temp=root.left;
root.left=root.right;
root.right=temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
class Solution(object):
def invertTree(self, root):
if root is None:
return root
root.left,root.right=root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
迭代
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return root;
}
Queue<TreeNode> qu=new LinkedList<>();
TreeNode tn;
int le;
qu.offer(root);
while(!qu.isEmpty()){
le=qu.size();
while(le>0){
tn=qu.poll();
if(tn.left!=null){
qu.offer(tn.left);
}
if(tn.right!=null){
qu.offer(tn.right);
}
TreeNode temp=tn.left;
tn.left=tn.right;
tn.right=temp;
le--;
}
}
return root;
}
}
class Solution(object):
def invertTree(self, root):
if root is None:
return root
qu=collections.deque()
qu.append(root)
while qu:
le=len(qu)
while le>0:
tn=qu.popleft()
if tn.left:
qu.append(tn.left)
if tn.right:
qu.append(tn.right)
tn.left,tn.right=tn.right,tn.left
le-=1
return root
写于皇清宣统辛亥后壹佰壹拾叁年拾月陆日
原文地址:https://blog.csdn.net/Runner__Binger/article/details/142730692
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!