二叉树的非递归遍历:
二叉树的非递归遍历使用栈或队列自身功能(先进后出或先进先出)来实现。对于非常深的树,递归可能导致栈溢出错误,因为每次递归调用都会占用栈空间。非递归遍历使用显式的栈或队列,可以更好地控制内存使用,避免这种问题。
链表节点:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int x) { val = x; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
以下写的几种方式都是非递归的(除了层次遍历用队列实现,其它都是用栈实现):
前序遍历
public class BinaryTree {
public void preorderTraversal(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode current = stack.pop();
System.out.print(current.val + " ");
if (current.right != null) {
stack.push(current.right);
}
if (current.left != null) {
stack.push(current.left);
}
}
}
}
中序遍历
public class BinaryTree {
public void inorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
current = stack.pop();
System.out.print(current.val + " ");
current = current.right;
}
}
}
后序遍历
public class BinaryTree {
public void postorderTraversal(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();
Stack<Integer> output = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode current = stack.pop();
output.push(current.val);
if (current.left != null) {
stack.push(current.left);
}
if (current.right != null) {
stack.push(current.right);
}
}
while (!output.isEmpty()) {
System.out.print(output.pop() + " ");
}
}
}
层次遍历
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue=new LinkedList<>();
List<List<Integer>> list = new ArrayList<List<Integer>>();
if (root == null)return list;
if(root!=null)queue.add(root);
while(!queue.isEmpty()){
List<Integer> tmp=new ArrayList<>();
for(int i=queue.size();i>0;i--){
TreeNode node=queue.poll();
tmp.add(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
list.add(tmp);
}
return list;
}
请大家不要忘记一键三连哟~~~
内容较少用了半个小时嘿嘿
如有不足请在评论区指出