您的位置:首页 > 编程语言 > Java开发

二叉树的深度优先遍历(递归、非递归),广度优先遍历(递归)

2017-12-05 10:53 148 查看
一、二叉树的深度优先遍历(DFS)有递归和非递归两种方法,递归很简单,先上递归代码

1.递归:

public void depthOrderTraversalWithRecursive()  

    {  

        depthTraversal(root);  

    }  

      

    private void depthTraversal(TreeNode tn)  

    {  

        if (tn!=null&&!tn.equals(null))   

        {  

            System.out.print(tn.value+"  ");  

            depthTraversal(tn.left);  

            depthTraversal(tn.right);  

        }         

    } 

递归思路很明显,就是先根,遍历左子树,遍历右子树,这和我博客前两篇文章递归创建二叉树的方法一样,核心就是3行。二叉树的深度优先遍历就是先序遍历

2.非递归:

非递归的DFS需要用到栈,利用栈的先进后出的特性,先将根节点入栈,栈不空时pop,然后右子树入栈,再左子树入栈。

/**
* 深度优先遍历,相当于先根遍历
* 采用非递归实现
* 需要辅助数据结构:栈
*/
public void depthOrderTraversal(){
if(root==null){
System.out.println("empty tree");
return;
}
ArrayDeque<TreeNode> stack=new ArrayDeque<TreeNode>();
stack.push(root);
while(stack.isEmpty()==false){
TreeNode node=stack.pop();
System.out.print(node.value+"    ");
if(node.right!=null){
stack.push(node.right);#####先入右子树
}
if(node.left!=null){
stack.push(node.left);#####后入左子树
}
}
System.out.print("\n");
}


二、二叉树的广度优先遍历,也就是层次遍历,用非递归比较简单,需要用到队列。先将根入队,队列不空时pop,然后入左子树,再入右子树

* 广度优先遍历
* 采用非递归实现
* 需要辅助数据结构:队列
*/
public void levelOrderTraversal(){
if(root==null){
System.out.println("empty tree");
return;
}
ArrayDeque<TreeNode> queue=new ArrayDeque<TreeNode>();
queue.add(root);
while(queue.isEmpty()==false){
TreeNode node=queue.remove();
System.out.print(node.value+"    ");
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
System.out.print("\n");
}


这些代码我都是直接复制粘贴网上大佬写好了的,我自己是用python写的递归的深度遍历,但是因为我代码中dfs只是个过程函数,没有单独写出来,所以不方便放在博客上,这些代码是帮助我以后复看理解的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息