剑指offer 面试题32 从上到下打印二叉树
2019-03-23 22:27
148 查看
从上到下打印二叉树
题目一
不分行从上到下打印二叉树:从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
class BinaryTreeNode{
int value;
BinaryTreeNode left;
BinaryTreeNode right;
}
思路
使用队列来完成,打印的同时也在往里面加入。
代码
public void fun(BinaryTreeNode root){ if(root==null){ return; } Queue<BinaryTreeNode> queue = new LinkedList<>(); queue.add(root); while(!queue.empty()){ BinaryTreeNode temp=queue.poll(); System.out.print(temp.value); if(temp.left != null){ queue.add(tempNode.left); } if(temp.right != null){ queue.add(tempNode.right);} } }
题目二
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印 ,每一层打印一行。
思路
同样是层序遍历,与上一题不同的是,此处要记录每层的节点个数,在每层打印结束后多打印一个回车符。
代码
public void fun(BinaryTreeNode root){ if(root==null){ return; } Queue<BinaryTreeNode> queue = new LinkedList<>(); queue.add(root); while(!queue.empty()){ for(int size=queue.size();size()>0;size--){ BinaryTreeNode temp=queue.poll(); System.out.print(temp.value); if(temp.left != null){ queue.add(tempNode.left); } if(temp.right != null){ queue.add(tempNode.right);} } System.out.println(); } }
题目三
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路
打印之字形的二叉树,需要两个栈。当我们在打印某一行结点时,把下一层的子结点保存到相应的栈里。如果当前打印的是奇数层,则先保存左子结点再保存右子结点到一个栈里;如果当前打印的是偶数层,则先保存右子结点再保存左子结点到第二个栈里。
代码public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> result = new ArrayList<>(); if (pRoot == null) return result; Stack<TreeNode> s1 = new Stack<>(); Stack<TreeNode> s2 = new Stack<>(); ArrayList<Integer> list = new ArrayList<>(); list.add(pRoot.val); result.add(list); s1.push(pRoot); while (s1.isEmpty() || s2.isEmpty()){ if (s1.isEmpty()&&s2.isEmpty()) break; ArrayList<Integer> tmp = new ArrayList<>(); if (s2.isEmpty()) { while (!s1.isEmpty()) { if (s1.peek().right != null) { tmp.add(s1.peek().right.val); s2.push(s1.peek().right); } if (s1.peek().left != null) { tmp.add(s1.peek().left.val); s2.push(s1.peek().left); } s1.pop(); } }else { while (!s2.isEmpty()) { if (s2.peek().left != null) { tmp.add(s2.peek().left.val); s1.push(s2.peek().left); } if (s2.peek().right != null) { tmp.add(s2.peek().right.val); s1.push(s2.peek().right); } s2.pop(); } } if(tmp.size()>0){ result.add(tmp); } } return result; }
相关文章推荐
- 剑指offer 面试题23 从上到下打印二叉树
- 《剑指Offer》面试题23:从上到下打印二叉树
- 剑指Offer面试题:21.从上到下打印二叉树
- 剑指Offer 面试题32:从上到下打印二叉树 Java代码实现
- 面试题32:从上到下打印二叉树
- half ok面试题32:从上到下打印二叉树
- 【剑指offer】面试题32:从上到下打印二叉树
- 【Java】面试题32:从上到下打印二叉树(顺序和在之字形)
- (剑指Offer)面试题23:从上到下打印二叉树
- 剑指offer面试题32:从上到下打印二叉树(c++ 完整代码)
- 剑指Offer(32)从上到下打印二叉树
- 剑指Offer-32:从上到下打印二叉树
- 【剑指offer】面试题32(2):分行从上到下打印二叉树
- 剑指offer系列之二十一:从上到下打印二叉树
- 《剑指offer》(面试题23):从上往下打印二叉树
- 面试题 23: 从上到下打印二叉树
- 剑指offer面试题23:从上到下打印二叉树
- 剑指offer之面试题23:从上往下打印二叉树
- 剑指offer-面试题23.从上往下打印二叉树
- 从上往下打印出二叉树的每个节点,同层节点从左至右打印(剑指offer,面试题32)