牛客网 二叉树的层序遍历

从上往下打印二叉树

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

c++

struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};
class Solution {
public:
    vector<int> PrintFromTopToBottom(TreeNode* root) {
        vector<int> ret;
        ret.clear();
        queue<TreeNode*> q;
        while(!q.empty())   q.pop();

        if(root!=NULL)
            q.push(root);
        else
            return ret;

        while(!q.empty()){
            TreeNode* cur=q.front();
            q.pop();
            if(cur->left!=NULL)
            q.push(cur->left);

            if(cur->right!=NULL)
            q.push(cur->right);
            ret.push_back(cur->val);
        }
        return ret;
    }
};

Java

import java.util.*;
/*
class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> ans=new ArrayList();
        Queue<TreeNode> q=new LinkedList<TreeNode>();
        if(root==null)
        	return ans;
        q.offer(root);
        while(!q.isEmpty()) {
        	TreeNode cur=q.poll();
        	
        	if(cur.left!=null)
        		q.offer(cur.left);
        	if(cur.right!=null)
        		q.offer(cur.right);
        	ans.add(cur.val);
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40507857/article/details/84553163