码迷,mamicode.com
首页 > 编程语言 > 详细

[算法]死磕二叉树专题算法

时间:2018-04-11 21:47:06      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:col   二叉树   非递归   empty   实现   his   static   后序遍历   一个栈   

1. 二叉树遍历(递归和非递归)

构造二叉树:

class Node{
    public String value;
    public Node left;
    public Node right;
    public Node(String value) {
        this.value = value;
    }
}

递归版前序遍历:

public static void preOrder(Node head){
        if(head != null){
            System.out.print(head.value + " ");
            preOrder(head.left);
            preOrder(head.right);
        }
    }

递归版中序遍历:

public static void inOrder(Node head){
        if(head != null){
            inOrder(head.left);
            System.out.print(head.value + " ");
            inOrder(head.right);
        }
    }

递归版后序遍历:

    public static void posOrder(Node head){
        if(head != null){
            posOrder(head.left);
            posOrder(head.right);
            System.out.print(head.value + " ");
        }
    }

非递归版前序遍历:

public static void preOrder(Node head){
        if(head != null){
            Stack<Node> stack = new Stack<>();
            stack.push(head);
            while(!stack.isEmpty()){
                Node pop = stack.pop();
                System.out.print(pop.value + " ");
                if(pop.right != null)
                    stack.push(pop.right);
                if(pop.left != null)
                    stack.push(pop.left);
            }
        }
    }

非递归版中序遍历:

    public static void inOrder(Node head){
        if(head != null){
            Stack<Node> stack = new Stack<>();
            while(!stack.isEmpty() || head != null){
                if(head != null){
                    stack.push(head);
                    head = head.left;
                }else{
                    head = stack.pop();
                    System.out.print(head.value + " ");
                    head = head.right;
                }
            }
        }
    }

非递归版后序遍历:

    public static void postOrder(Node head){
        if(head != null){
            Stack<Node> stack1 = new Stack<>();
            Stack<Node> stack2 = new Stack<>();
            stack1.push(head);
            while(!stack1.isEmpty()){
                Node pop = stack1.pop();
                stack2.push(pop);
                if(pop.left != null){
                    stack1.push(pop.left);
                }
                if(pop.right != null){
                    stack1.push(pop.right);
                }
            }
            while(!stack2.isEmpty()){
                System.out.print(stack2.pop().value + " ");
            }
        }
    }

这里用了两个栈,其实一个栈也能实现,这里这样做是因为可以和前序遍历对比着记,比较容易。

[算法]死磕二叉树专题算法

标签:col   二叉树   非递归   empty   实现   his   static   后序遍历   一个栈   

原文地址:https://www.cnblogs.com/DarrenChan/p/8798412.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!