<>从上往下打印二叉树
<https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=11175&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking>
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
<>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; } }
热门工具 换一换