二叉樹S型遍歷的Java實現-雙棧
阿新 • • 發佈:2020-07-27
今天看到群裡有人討論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> leftStack = new Stack<>(); // 單數層,從右開始遍歷,先取右子樹 Stack<Node> rightStack = new Stack<>(); // 偶數層,從左開始遍歷,先取左子樹 rightStack.push(root); while (!leftStack.isEmpty() || !rightStack.isEmpty()){ if (!leftStack.isEmpty()){ // 從左開始遍歷,先取左子樹 while (!leftStack.isEmpty()){ Node node = leftStack.pop(); System.out.print(node.getValue() + " "); if (node.getLchild() != null){ rightStack.push(node.getLchild()); } if (node.getRchild() != null){ rightStack.push(node.getRchild()); } } } else { // 從右開始遍歷,先取右子樹 while (!rightStack.isEmpty()){ Node node = rightStack.pop(); System.out.print(node.getValue() + " "); if (node.getRchild() != null){ leftStack.push(node.getRchild()); } if (node.getLchild() != null){ leftStack.push(node.getLchild()); } } } } 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; } } }