二叉树前序非递归遍历
Posted notesbuddy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树前序非递归遍历相关的知识,希望对你有一定的参考价值。
1 package com.basic.bt; 2 3 import java.util.ArrayList; 4 import java.util.Stack; 5 6 /** 7 * Created by mac on 2017/1/19. 8 */ 9 public class PreOrderBT { 10 11 public ArrayList<Integer> result = new ArrayList<>(); 12 public ArrayList<Integer> pre = new ArrayList<>(); 13 15 public void preOrder(TreeNode root) { 16 if(root == null) { 17 return; 18 } 19 //访问跟 -> 左孩子 -> 右孩子 20 result.add(root.val); 21 preOrder(root.left); 22 preOrder(root.right); 23 } 24 25 // no recursion 26 public void preOrderTraversal(TreeNode root) 27 { 28 if(root == null) { 29 return; 30 } 31 Stack<TreeNode> stack = new Stack<TreeNode>(); 32 stack.push(root); 33 while(!stack.isEmpty()) { 34 TreeNode node = stack.pop(); 35 pre.add(node.val); 36 if(node.right != null) { 37 stack.push(node.right); 38 } 39 if(node.left != null) { 40 stack.push(node.left); 41 } 42 } 43 44 } 45 46 public static void main(String[] args) { 47 PreOrderBT pre = new PreOrderBT(); 48 TreeNode root = new TreeNode(0); 49 TreeNode node1 = new TreeNode(1); 50 TreeNode node2 = new TreeNode(2); 51 TreeNode node3 = new TreeNode(3); 52 TreeNode node4 = new TreeNode(4); 53 54 root.left = node1; 55 root.right = node2; 56 node1.left = node3; 57 node1.right =node4; 58 pre.preOrderTraversal(root); 59 for(int i = 0; i < pre.pre.size(); i++) { 60 System.out.println(pre.pre.get(i)); 61 } 62 } 63 64 }
以上是关于二叉树前序非递归遍历的主要内容,如果未能解决你的问题,请参考以下文章