java⼆叉树的遍历(代码实现)⼀、前序遍历
访问顺序:先根节点,再左⼦树,最后右⼦树;
1)递归实现
public void preOrderTraver1(TreeNode root) {
if (root != null) {
System.out.print(root.val + "->");
preOrderTraver1(root.left);
preOrderTraver1(root.right);
}
}
2)⾮递归实现
public void preOrderTraver2(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while (node != null || !pty()) {
if (node != null) {
System.out.print(node.val + "->");
stack.push(node);
node = node.left;
} el {
TreeNode tem = stack.pop();
node = tem.right;
}
}
}
⼆、中序遍历
访问顺序:先左⼦树,再根节点,最后右⼦树;
1)递归实现
格兰仕微波炉怎么使用public void inOrderTraver(TreeNode root) {
if (root != null) {
inOrderTraver(root.left);
System.out.print(root.val + "->");
inOrderTraver(root.right);
}
}
2)⾮递归实现
public void inOrderTraver(TreeNode root) {
认知突围
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while (node != null || !stack.isEmpty()) {
if (node != null) {
stack.push(node);
node = node.left;
} el {
TreeNode tem = stack.pop();
System.out.print(tem.val + "->");
node = tem.right;
}
}
}
三、后序遍历
访问顺序:先左⼦树,再右⼦树,最后根节点,上图的访问结果为:AEFDHZMG。1)递归实现
public void postOrderTraver(TreeNode root) {
if (root != null) {
postOrderTraver(root.left);
postOrderTraver(root.right);
System.out.print(root.val + "->");
}
自律用英语怎么说}
2)⾮递归实现
public void postOrderTraver(TreeNode root) {
TreeNode cur, pre = null;
Stack<TreeNode> stack = new Stack<>();
内裤外穿stack.push(root);
while (!pty()) {
cur = stack.peek();
if ((cur.left == null && cur.right == null) || (pre != null && (pre == cur.left || pre == cur.right))) { System.out.print(cur.val + "->");
stack.pop();生日快乐词
pre = cur;
} el {
if (cur.right != null)
stack.push(cur.right);
if (cur.left != null)
stack.push(cur.left);
}
}
}
四、层次遍历
public void levelOrderTraver(TreeNode root) {
if (root == null) {
return;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
茶壶山TreeNode node = queue.poll();
System.out.print(node.val + "->");
关于生命的句子if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}acwifi
}