算法题之二叉树的锯齿形层次遍历
题目描述:给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)
解题思路:
1)这里可以先使用第一个栈来保存二叉树第一层扫描的结果,然后弹出结点,
2)接着按左右子节点存入第二个栈;接着依次弹出第二个栈结点,按着右左子节点存入第一个栈;
3)依照上面步骤依次处理二叉树结点,直到二叉树结点处理完
package com.wc.tree; //树结构 public class TreeNode { TreeNode left; TreeNode right; int value; public TreeNode(int v) { this.value = v; } public TreeNode getLeft() { return left; } public void setLeft(TreeNode left) { this.left = left; } public TreeNode getRight() { return right; } public void setRight(TreeNode right) { this.right = right; } }
package com.wc.tree; import java.util.LinkedList; import java.util.List; import java.util.Stack; public class Tree { //扫描方法 public static List<Integer> scanTree(TreeNode root) { if(root == null) return null; List<Integer> list = new LinkedList<>(); //判断输出是否反转 boolean isReverse = false; //保存从左到右输出二叉树结点 Stack<TreeNode> stack = new Stack<>(); //保存从右到左输出二叉树结点 Stack<TreeNode> stackTwo = new Stack<>(); stack.push(root); while(!stack.isEmpty() || !stackTwo.isEmpty()) { if(!isReverse) { System.out.print("["); while(!stack.isEmpty()) { TreeNode scanNode = stack.pop(); System.out.print(scanNode.value + " "); list.add(scanNode.value); //存入第二个栈 if(scanNode.left != null) stackTwo.push(scanNode.left); if(scanNode.right != null) stackTwo.push(scanNode.right); } System.out.println("],"); isReverse = true; } else { System.out.print("["); while(!stackTwo.isEmpty()) { TreeNode scanNode = stackTwo.pop(); System.out.print(scanNode.value + " "); list.add(scanNode.value); //存入第一个栈 if(scanNode.right != null) stack.push(scanNode.right); if(scanNode.left != null) stack.push(scanNode.left); } System.out.println("],"); isReverse = false; } } return list; } }
package com.wc.test; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.wc.tree.Tree; import com.wc.tree.TreeNode; //测试代码 public class TreeScanTest { private TreeNode rootNode; @Before public void setUp() throws Exception { TreeNode root = new TreeNode(3); TreeNode n1 = new TreeNode(9); TreeNode n2 = new TreeNode(20); root.setLeft(n1); root.setRight(n2); TreeNode n3 = new TreeNode(15); TreeNode n4 = new TreeNode(7); n2.setLeft(n3); n2.setRight(n4); rootNode = root; } @After public void tearDown() throws Exception { } @Test public void testScanTree() { List result = Tree.scanTree(rootNode); List<Integer> expectResult=new ArrayList(); expectResult.add(3); expectResult.add(20); expectResult.add(9); expectResult.add(15); expectResult.add(7); assertEquals(expectResult, result); } }
打印结果如下:
posted on 2018-02-27 21:11 willowWind 阅读(1323) 评论(0) 编辑 收藏 举报