码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树中序非递归遍历

时间:2017-01-20 20:29:35      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:[]   null   blog   roo   integer   非递归遍历   stack   size   push   

package com.basic.bt;

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

/**
 * Created by mac on 2017/1/19.
 */
public class InOrderBT {

    ArrayList<Integer> result = new ArrayList<Integer>();
    ArrayList<Integer> traversal = new ArrayList<Integer>();


    public void inorder(TreeNode root) {

        if(root == null) {
            return;
        }
        inorder(root.left);
        result.add(root.val);
        inorder(root.right);
    }

    public void inorderTraversal(TreeNode root) {
        if(root == null)
        {
            return;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        while(root != null || !stack.isEmpty())
        {
            while(root != null) {
            stack.push(root);
            root = root.left;
            }
            TreeNode tmp = stack.peek();
            traversal.add(tmp.val);
            stack.pop();
            root = tmp.right;
        }
    }

    public  static void main(String[] args) {
        InOrderBT in = new InOrderBT();
        TreeNode root = new TreeNode(0);
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);

        root.left = node1;
        root.right = node2;
        node1.left = node3;
        node1.right =node4;

        in.inorderTraversal(root);

        for(int i = 0; i < in.traversal.size(); i++) {
            System.out.println(in.traversal.get(i));
        }

    }
}

  

二叉树中序非递归遍历

标签:[]   null   blog   roo   integer   非递归遍历   stack   size   push   

原文地址:http://www.cnblogs.com/superzhaochao/p/6323711.html

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