java实现二叉树的深度和广度遍历

二叉树的节点结构:

public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}

建树:

public static void insert(TreeNode root, int val) {// 向二叉树中插入子节点
		if (val > root.val) {// 二叉树的左节点都比根节点小
			if (root.right == null) {
				root.right = new TreeNode(val);
			} else {
				insert(root.right, val);
			}
		} else { // 二叉树的右节点都比根节点大
			if (root.left == null) {
				root.left = new TreeNode(val);
			} else {
				insert(root.left, val);
			}
		}
	}

前序递归实现:

public static void preOrder(TreeNode root) { // 前序遍历
		if (root != null) {
			System.out.print(root.val + "-");
			preOrder(root.left);
			preOrder(root.right);
		}
	}

前序非递归实现:

public static void preStackIterator(TreeNode root) {
		Stack<TreeNode> stack = new Stack<>();
		if (root == null)
			return;
		stack.push(root);
		while (!stack.isEmpty()) {
			TreeNode temp = stack.pop();
			System.out.print(temp.val + " ");
			if (temp.right != null)
				stack.push(temp.right);
			if (temp.left != null)
				stack.push(temp.left);
		}
	}

中序递归实现:

public static void inOrder(TreeNode root) { // 前序遍历
		if (root != null) {
			inOrder(root.left);
			System.out.print(root.val + "-");
			inOrder(root.right);
		}
	}

中序非递归实现:

public static void inStackIterator(TreeNode root) {
		Stack<TreeNode> stack = new Stack<>();
		if (root == null)
			return;
		TreeNode temp = root;
		while (!stack.isEmpty() || temp != null) {
			while (temp != null) {
				stack.push(temp);
				temp = temp.left;
			}
			temp = stack.pop();
			System.out.print(temp.val + " ");
			if (temp.right != null)
				temp = temp.right;
			else
				temp = null;
		}
	}

后序递归实现:

public static void postOrder(TreeNode root) { // 前序遍历
		if (root != null) {
			postOrder(root.left);
			postOrder(root.right);
			System.out.print(root.val + "-");
		}
	}

后序非递归实现:

public static void postStackIterator(TreeNode root) {
		Stack<TreeNode> stack = new Stack<>();
		if (root == null)
			return;
		TreeNode temp = root;
		stack.push(temp);
		TreeNode ptr = root, pre = null;
		while (!stack.isEmpty()) {
			ptr = stack.peek();
			if (pre != ptr.right && pre != ptr.left) {
				if (ptr.right != null)
					stack.push(ptr.right);
				if (ptr.left != null)
					stack.push(ptr.left);
			}
			if (ptr.left == null && ptr.right == null || pre == ptr.left
					|| pre == ptr.right) {
				System.out.print(ptr.val + " ");
				stack.pop();
			}
			pre = ptr;
		}
	}

广度优先遍历:

public static void preListIterator(TreeNode root) {
		ArrayList<TreeNode> list = new ArrayList<>();
		if (root == null)
			return;
		list.add(root);
		while (!list.isEmpty()) {
			TreeNode temp = list.remove(0);
			System.out.print(temp.val + " ");
			if (temp.left != null)
				list.add(temp.left);
			if (temp.right != null)
				list.add(temp.right);
		}
	}
发布了21 篇原创文章 · 获赞 10 · 访问量 8090

猜你喜欢

转载自blog.csdn.net/weixin_44997483/article/details/103507526
今日推荐