-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvertBinaryTree.java
More file actions
54 lines (43 loc) · 1.19 KB
/
Copy pathInvertBinaryTree.java
File metadata and controls
54 lines (43 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.LinkedList;
import java.util.Queue;
/*
* 求对称二叉树(即镜像)
* 思路: 利用递归
*/
public class InvertBinaryTree {
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int x){
this.val=x;
}
}
public static TreeNode invertTree(TreeNode root){
if(root==null) return null;
if(root.left==null && root.right==null) return root;
//交换
TreeNode node=root.left;
root.left =root.right;
root.right=node;
invertTree(root.left);
invertTree(root.right);
return root;
}
// 按层遍历二叉树,从左到右一次打印 利用队列
public static void levelTraverse(TreeNode root){
Queue<TreeNode> queue=new LinkedList<TreeNode>();
if(root==null)return;
queue.offer(root);
while(queue.size()>0){
TreeNode tempNode=queue.poll();
System.out.print(tempNode.val+" ");
if(tempNode.left!=null){
queue.offer(tempNode.left);
}
if(tempNode.right!=null){
queue.offer(tempNode.right);
}
}
}
}