二叉树的深度优先搜索,深度优先遍历,Java递归和非递归实现。

import java.util.ArrayList;
import java.util.Stack;

public class BianryTreeDFS {

    /**
     * 二叉树的深度优先搜索,递归实现,也就是二叉树的先序遍历
     * @param tree 二叉树
     */
    public static void preOrderDFS(BinaryTree tree){
        if(tree == null){
            return;
        }
        System.out.println(tree.value);
        preOrderDFS(tree.left);
        preOrderDFS(tree.right);
    }

    /**
     * 二叉树的深度优先搜索,非递归实现
     * @param binaryTree 二叉树
     */
    public static void preOrderDFS02(BinaryTree binaryTree){
        Stack<BinaryTree> stack = new Stack<>();
        if(binaryTree != null){
            stack.push(binaryTree);
        }
        BinaryTree node = null;
        while(!stack.isEmpty()){
            node = stack.pop();
            System.out.println(node.value);
            if(node.right != null){
                stack.push(node.right);
            }
            if(node.left != null){
                stack.push(node.left);
            }
        }
    }

    /**
     * 二叉树的深度优先搜索,非递归实现使用分治算法
     * @param tree 二叉树
     */
    public static ArrayList<Integer> preOrderDFS03(BinaryTree tree){
        ArrayList<Integer> list =new ArrayList<>();
        if(tree == null){
            return list;
        }

        ArrayList<Integer> left = preOrderDFS03(tree.left);
        ArrayList<Integer> right = preOrderDFS03(tree.right);

        list.add(tree.value);
        list.addAll(left);
        list.addAll(right);
        return list;
    }

    public static void main(String[] args){

        BinaryTree head  = new BinaryTree(1);
        BinaryTree left  = new BinaryTree(2);
        BinaryTree right  = new BinaryTree(3);
        BinaryTree left01  = new BinaryTree(4);
        BinaryTree right01  = new BinaryTree(5);
        head.left = left;
        head.right = right;
        left.left = left01;
        left.right = right01;

        preOrderDFS(head);
        System.out.println("-----------");
        preOrderDFS02(head);
        System.out.println("-----------");
        ArrayList<Integer> list = preOrderDFS03(head);
        System.out.println(list.toString());
        //测试结果[1, 2, 4, 5, 3]
    }
}

//二叉树的类
class BinaryTree{
    int value;
    BinaryTree left;
    BinaryTree right;

    public BinaryTree(int value){
        left = null;
        right = null;
        this.value = value;
    }
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值