Skip to content

Commit 92c7b10

Browse files
增加二叉树的常用操作
1 parent 27b72f9 commit 92c7b10

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package datastructure.tree;
2+
3+
import common.TreeNode;
4+
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
8+
public class BinaryTree {
9+
//递归算法-前序遍历(中序、后序稍作改动)
10+
private List<Integer> list=new ArrayList<>();
11+
public List<Integer> preorderTraversal(TreeNode root) {
12+
if(root!=null){
13+
list.add(root.val);
14+
preorderTraversal(root.left);
15+
preorderTraversal(root.right);
16+
}
17+
return list;
18+
}
19+
//递归算法-树的最大深度
20+
public int maxDepth(TreeNode root){
21+
if(root==null){
22+
return 0;
23+
}
24+
int left=maxDepth(root.left);
25+
int right=maxDepth(root.right);
26+
return 1+Math.max(left,right);
27+
}
28+
//递归算法-检查二叉树否是对称。
29+
public boolean isSymmetric(TreeNode root) {
30+
return isMirror(root,root);
31+
}
32+
public boolean isMirror(TreeNode node1,TreeNode node2){
33+
if(node1==null&&node2==null){
34+
return true;
35+
}
36+
if(node1==null||node2==null){
37+
return false;
38+
}
39+
return (node1.val==node2.val)&&isMirror(node1.left,node2.right)&&isMirror(node1.right,node2.left);
40+
}
41+
//给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
42+
public boolean hasPathSum(TreeNode root, int sum) {
43+
if(root == null){
44+
return false;
45+
}
46+
if(root.left == null && root.right == null){
47+
return sum - root.val == 0;
48+
}
49+
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
50+
}
51+
//从中序与后序遍历序列构造二叉树
52+
public TreeNode buildTree(int[] inorder, int[] postorder) {
53+
if(postorder.length==0||inorder.length==0){
54+
return null;
55+
}
56+
57+
if(postorder.length!=inorder.length){
58+
return null;
59+
}
60+
61+
int rootVal=postorder[postorder.length-1];
62+
TreeNode root=new TreeNode(rootVal);
63+
int rootIndex=-1;
64+
for(int i=0;i<inorder.length;i++){
65+
if(inorder[i]==rootVal){
66+
rootIndex=i;
67+
break;
68+
}
69+
}
70+
//也可以不用这么多temp数组,直接操作原数组,给定startIndex和endIndex,这样的话,参数是6个,但执行效率更快。
71+
int[] inorderLeft=new int[rootIndex];
72+
int[] inorderRight=new int[inorder.length-rootIndex-1];
73+
int[] postorderLetf=new int[rootIndex];
74+
int[] postorderRight=new int[inorder.length-rootIndex-1];
75+
for(int i=0;i<rootIndex;i++){
76+
inorderLeft[i]=inorder[i];
77+
postorderLetf[i]=postorder[i];
78+
}
79+
int j=0;
80+
for(int k=rootIndex+1;k<inorder.length;k++,j++){
81+
inorderRight[j]=inorder[k];
82+
postorderRight[j]=postorder[k-1];
83+
}
84+
85+
root.left=buildTree(inorderLeft,postorderLetf);
86+
root.right=buildTree(inorderRight,postorderRight);
87+
return root;
88+
}
89+
}
90+

0 commit comments

Comments
 (0)