#数据结构与算法学习笔记#剑指Offer21:从上往下打印二叉树/层次遍历二叉树(Java、C/C++)

版权声明:本文为博主NJU_ChopinXBP原创文章,发表于CSDN,仅供交流学习使用,转载请私信或评论联系,未经博主允许不得转载。感谢您的评论与点赞。 https://blog.csdn.net/qq_20304723/article/details/81869533

2018.8.20

这道题实际上以前做过一模一样的——#数据结构与算法学习笔记#PTA10:层次遍历叶节点(JAVA)

方法也很经典,创建一个队列,先压入根节点,然后不断弹出结点。每弹出一个结点同时压入该结点的左右子结点。从而可以实现层次遍历。同样的方法还可以用于BFS广度优先搜索——#数据结构与算法学习笔记#PTA18:图(邻接表)+DFS(深度优先搜索)+BFS(广度优先搜索)(C/C++)


题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。


Java实现:

/**
 * 
 * @author ChopinXBP 
 * 从上往下打印出二叉树的每个节点,同层节点从左至右打印。
 *
 *
 */

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;


public class PrintFromTopToBottom_21 {

	public static class TreeNode {
	    int val = 0;
	    TreeNode left = null;
	    TreeNode right = null;
	    public TreeNode(int val) {
	        this.val = val;
	    }
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeNode root = new TreeNode(0);
		Init(root);
		ArrayList<Integer> result = Solution(null);
		for(int i = 0; i < result.size(); i++){
			System.out.print(result.get(i));
		}
	}
	
	public static TreeNode Init(TreeNode root){		
		TreeNode pNode = root;
		pNode.left = new TreeNode(1);
		pNode.right = new TreeNode(2);
		pNode = root.left;
		pNode.left = new TreeNode(3);
		pNode.right = new TreeNode(4);
		pNode = root.right;
		pNode.left = new TreeNode(5);
		pNode.right = new TreeNode(6);
		pNode = root.left.left;
		pNode.left = new TreeNode(7);
		pNode.right = new TreeNode(8);
		pNode = root.right.left;
		pNode.left = new TreeNode(9);
		return root;
	}
	
	public static ArrayList<Integer> Solution(TreeNode root){
		ArrayList<Integer> result = new ArrayList<>();
		if(root == null) return result;
				
		Queue<TreeNode> queue = new LinkedList<TreeNode>();
		queue.add(root);
		
		while(!queue.isEmpty()){
			TreeNode newnode = queue.poll();
			result.add(newnode.val);
			if(newnode.left != null) queue.add(newnode.left);
			if(newnode.right != null) queue.add(newnode.right);
		}
		return result;
	}
}

C++实现示例:

class Solution {
public:
    vector<int> PrintFromTopToBottom(TreeNode *rt) {
        queue<TreeNode*> q;
        q.push(rt);
        vector<int> r;
        while(!q.empty()){
            rt = q.front(); q.pop();
            if(!rt) continue;
            r.push_back(rt -> val);
            q.push(rt -> left);
            q.push(rt -> right);
        }
        return r;
    }
};

#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

猜你喜欢

转载自blog.csdn.net/qq_20304723/article/details/81869533