先定义好结构体 先定义好根节点 TreeNode root;
//添加
public TreeNode insert(int val) {
System.out.print("->"+val);
TreeNode newRoot = new TreeNode(val);
if (root == null) {
root = newRoot;
return root;
}
TreeNode temp = root;
while (true) {
TreeNode parent = temp;
if (temp.getVal() < val) {
temp = temp.getRightChild();
if (temp == null) {
parent.setRightChild(newRoot);
return root;
}
} else {
temp = temp.getLeftChild();
if (temp == null) {
parent.setLeftChild(newRoot);
return root;
}
}
}
}
二叉树的便利
//先序
public void front(TreeNode treeNode) {
if (treeNode != null) {
System.out.print(treeNode.getVal());
front(treeNode.getLeftChild());
front(treeNode.getRightChild());
}
}
//中序
public void order(TreeNode treeNode) {
if (treeNode != null) {
order(treeNode.getLeftChild());
System.out.print(treeNode.getVal());
order(treeNode.getRightChild());
}
}
//后序
public void end(TreeNode treeNode) {
if (treeNode != null) {
end(treeNode.getLeftChild());
end(treeNode.getRightChild());
System.out.print(treeNode.getVal());
}
}
示例:
输出结果: