P28-二叉樹遍歷-中序-迭代
阿新 • • 發佈:2022-04-11
//二叉樹遍歷 /* * 前序遍歷:根左右 * 中序遍歷:左根右 * 後序遍歷:左右根 * 層序遍歷:從上往下、從左往右 * * 遞迴遍歷:使用遞迴方法遍歷 * 迭代遍歷:使用迭代方法實現遞迴函式,與遞迴等價 * morris遍歷 * */ public class P28 { /* * 1 * / \ * 2 3 * / \ * 4 5 * / \ * 6 7 * */ publicstatic void main(String[] args) { TreeNode node7 = new TreeNode(7, null, null); TreeNode node6 = new TreeNode(6, null, null); TreeNode node5 = new TreeNode(5, node6, node7); TreeNode node4 = new TreeNode(4, null, null); TreeNode node3 = new TreeNode(3, null, null); TreeNode node2 = new TreeNode(2, node4, node5); TreeNode node1 = new TreeNode(1, node2, node3); iter(node1); } //中序-迭代 //4-2-6-5-7-1-3 public static void iter(TreeNode root){ if(root != null){ Stack<TreeNode> stack = new Stack<>();while(!stack.isEmpty() || root != null){ if(root != null){ stack.push(root); //不停讓左節點進棧 root = root.left; }else{ //知道左節點是null root = stack.pop(); //變回父節點 System.out.println(root.val); //輸出父節點 root = root.right; //開始右邊孩子 } } } } static class TreeNode{ int val; TreeNode left; TreeNode right; int deep; TreeNode(){} TreeNode(int val){ this.val = val; } TreeNode(int val, TreeNode left, TreeNode right){ this.val = val; this.left = left; this.right = right; } } }