今天看到群里有人讨论S型遍历二叉树问题,写了个demo。
思路分析:
1、奇数层节点从右往左,偶数层节点从左往右
2、(双栈)奇数层、偶数层分别维护一个栈。
遍历奇数层时,向偶数层的栈内push数据,先push右子节点
遍历偶数层时,向奇数层的栈内push数据,先push左子节点
3、循环直至两个栈都为空。
demo代码如下:
public class BinaryTreeTraversalTests { private Node root; @Before public void init(){ System.out.println("构建二叉树"); Node node1 = new Node(1, null, null); Node node2 = new Node(2, null, null); Node node3 = new Node(3, null, null); Node node4 = new Node(4, null, null); Node node5 = new Node(5, null, null); Node node6 = new Node(6, null, null); Node node7 = new Node(7, null, null); Node node8 = new Node(8, null, null); Node node9 = new Node(9, null, null); Node node10 = new Node(10, null, null); root = node1; node1.setLchild(node2); node1.setRchild(node3); node2.setLchild(node4); node3.setLchild(node5); node3.setRchild(node6); node4.setRchild(node7); node5.setLchild(node8); node5.setRchild(node9); node6.setRchild(node10); System.out.println("-----------"); } /** * 广度优先遍历 */ @Test public void breadthFirst(){ Queue<Node> nodes = new LinkedList<>(); nodes.add(root); while (!nodes.isEmpty()){ Node node = nodes.remove(); System.out.print(node.getValue() + " "); if (node.getLchild() != null){ nodes.add(node.getLchild()); } if (node.getRchild() != null){ nodes.add(node.getRchild()); } } System.out.println(); System.out.println("================="); } /** * s型遍历 */ @Test public void breadthFirst_s(){ Stack<Node> oddStack = new Stack<>(); // 奇数层,从右开始遍历,先取右子树 Stack<Node> evenStack = new Stack<>(); // 偶数层,从左开始遍历,先取左子树 oddStack.push(root); // 根节点push第一层 while (!oddStack.isEmpty() || !evenStack.isEmpty()){ if (!oddStack.isEmpty()){ // 从右开始遍历,先取右子树 while (!oddStack.isEmpty()){ Node node = oddStack.pop(); System.out.print(node.getValue() + " "); if (node.getRchild() != null){ evenStack.push(node.getRchild()); } if (node.getLchild() != null){ evenStack.push(node.getLchild()); } } } else { // 从左开始遍历,先取左子树 while (!evenStack.isEmpty()){ Node node = evenStack.pop(); System.out.print(node.getValue() + " "); if (node.getLchild() != null){ oddStack.push(node.getLchild()); } if (node.getRchild() != null){ oddStack.push(node.getRchild()); } } } } System.out.println(); System.out.println("================="); } public class Node{ private int value; private Node Lchild; private Node Rchild; public Node(int value, Node lchild, Node rchild) { this.value = value; Lchild = lchild; Rchild = rchild; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public Node getLchild() { return Lchild; } public void setLchild(Node lchild) { Lchild = lchild; } public Node getRchild() { return Rchild; } public void setRchild(Node rchild) { Rchild = rchild; } } }
原文:https://www.cnblogs.com/sunnyjarry/p/13385244.html