算法(三)

1、二叉树深度优先遍历、广度优先遍历

二叉树深度优先遍历前序、中序、后序),此处采用中序。代码如下:

#递归版本

public void inOrderTraverse1(TreeNode root){

if(root!=null){

System.out.print(root.val);

inOrderTraverse1(root.left);

inOrderTraverse1(root.right);

}

}

#非递归版本

public void preOrderTraverse2(TreeNode root) {  

LinkedList<TreeNode> stack = new LinkedList<>();  

    TreeNode pNode = root;  

    while (pNode != null || !stack.isEmpty()) {  

     if (pNode != null) {  

         System.out.print(pNode.val+"  ");  

            stack.push(pNode);  

            pNode = pNode.left;  

        } else if(pNode == null && !stack.isEmpty()){

         TreeNode node = stack.pop();  

            pNode = node.right;  

        }  

    }  

}  

 

#二叉树广度优先遍历(层次遍历),代码如下:

public void levelTraverse(TreeNode root){

if(root == null){

return;

}

LinkedList<TreeNode> queue = new LinkedList<>();

queue.offer(root);

while(!queue.isEmpyt()){

TreeNode node = queue.poll();

System.out.print(node.val + );

if(node.left != null){

queue.offer(root.left);

}

if(node.right != null){

queue.offer(root.right);

}

}

}

 

#二叉树广度优先遍历(层次遍历),代码如下:

public void depthOrderTraverse(TreeNode root) {  

        if (root == null) {  

            return;  

        }  

        LinkedList<TreeNode> stack = new LinkedList<>();  

        stack.push(root);  

        while (!stack.isEmpty()) {  

            TreeNode node = stack.pop();  

            System.out.print(node.val+"  ");  

            if (node.right != null) {  

                stack.push(node.right);  

            }  

            if (node.left != null) {  

                stack.push(node.left);  

            }  

        }  

算法 文章被收录于专栏

根据自己所见所闻进行算法归纳总结

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-08 12:05
俺不中了,BOSS遇到了一个hr,我觉得我咨询的问题都很正常吧,然后直接就被拒绝了???
恶龙战士:你问的太多了,要不就整理成一段话直接问他,一个一个问不太好
点赞 评论 收藏
分享
点赞 评论 收藏
分享
lllllkin:感觉可以精简到一页简历,有些排版感觉不是必须的。 时间线越早的,你自己越熟悉的放前面。描述可以更精简些,一些问题解决感觉可以不用写具体技术栈,卖个关子,等面试官问。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务