剑指offer-22-从上往下打印二叉树(递归)
从上往下打印二叉树
http://www.nowcoder.com/questionTerminal/7fe2212963db4790b57431d9ed259701
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
题目给了提示用队列,大部分题解也是用队列,这里尝试用递归做一下。
代码不够简洁,结果还行哈哈哈
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> a = new ArrayList<Integer>();
if (root == null)
return a;
a.add(root.val);
leftandright( a, root);
return a;
}
public ArrayList<Integer> leftandright(ArrayList a,TreeNode root) {
if (root.left != null)
a.add(root.left.val);
if (root.right != null)
a.add(root.right.val);
if(root.left != null)
leftandright( a, root.left);
if(root.right != null)
leftandright( a, root.right);
return a;
}
}

韶音科技公司氛围 663人发布