二叉树的前序遍历、中序遍历、后序遍历、深度优先搜索、广度优先搜索

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

前序遍历(Pre-order)

public void preorder(TreeNode root) {
	if(root != null){
		System.out.println(root.val);
		preorder(root.left);
		preorder(root.right);
	}
}

中序遍历(In-order)

public void inorder(TreeNode root) {
	if(root != null){
		inorder(root.left);
		System.out.println(root.val);
		inorder(root.right);
	}
}

后序遍历(Post-order)

public void postorder(TreeNode root) {
	if(root != null){
		postorder(root.left);
		postorder(root.right);
		System.out.println(root.val);
	}
}

广度优先搜索(BFS)

广度优先搜索(Breadth-First-Search)从根节点开始,一层一层的访问,比较符合直观想法。
使用队列先进先出的特性,访问某一层节点后,将此层节点出队,将其子节点依次入队。如此循环。

public void BFS(TreeNode root){
	if (root == null) {  
		return;  
    }  
    LinkedList<TreeNode> queue = new LinkedList<>();  
    queue.offer(root);  
    while (!queue.isEmpty()) {  
    	TreeNode node = queue.poll();  
	    System.out.println(node.val);  
    	if (node.left != null)
	    	queue.offer(node.left);  
        if (node.right != null)
        	queue.offer(node.right); 
    }  
}

深度优先搜索(DFS)

深度优先搜索(Depth-First-Search)符合计算机的处理方式,使用栈结构。

public void BFS(TreeNode root){
	if (root == null) {  
		return;  
    }  
    LinkedList<TreeNode> stack = new LinkedList<>();  
    stack.push(root);
    while(!stack.isEmpty()){
    	TreeNode node = stack.pop();
    	system.out.println(node.val);
    	if(node.right!=null)
    		stack.push(node.right);
    	if(node.left!=null)
    		stack.push(node.left);
    }  
}

参考连接:https://leetcode.com/problems/validate-binary-search-tree/solution/

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值