按之字形順序打印二叉樹
題目描述
請實現一個函數按照之字形打印二叉樹,即第一行按照從左到右的順序打印,第二層按照從右至左的順序打印,第三行按照從左到右的順序打印,其他行以此類推。
思路
- 根據題意,每行的節點的訪問順序是相反的,我們可以用兩個棧來隔行存儲,一個棧中根據“左結點->右結點”的順序訪問另一個棧的棧頂元素,而另一個棧根據“右子樹->左子樹”的順序訪問另一個棧的棧頂元素,直到兩個棧都為空
代碼
import java.util.ArrayList; import java.util.Stack; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (pRoot == null) { return result; } Stack<TreeNode> stack1 = new Stack<TreeNode>(); Stack<TreeNode> stack2 = new Stack<TreeNode>(); ArrayList<Integer> list = new ArrayList<Integer>(); list.add(pRoot.val); result.add(list); stack1.push(pRoot); while (stack1.isEmpty() || stack2.isEmpty()) { if (stack1.isEmpty() && stack2.isEmpty()) { break; } ArrayList<Integer> temp = new ArrayList<Integer>(); if (stack2.isEmpty()) { while (!stack1.isEmpty()) { if (stack1.peek().right != null) { temp.add(stack1.peek().right.val); stack2.push(stack1.peek().right); } if (stack1.peek().left != null) { temp.add(stack1.peek().left.val); stack2.push(stack1.peek().left); } stack1.pop(); } } else { while (!stack2.isEmpty()) { if (stack2.peek().left != null) { temp.add(stack2.peek().left.val); stack1.push(stack2.peek().left); } if (stack2.peek().right != null) { temp.add(stack2.peek().right.val); stack1.push(stack2.peek().right); } stack2.pop(); } } if (temp.size() > 0) { result.add(temp); } } return result; } }