题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

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

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

}

} */ public class Solution { public ArrayList<ArrayList > Print(TreeNode pRoot) { ArrayList<ArrayList> list = new ArrayList<>(); depth(pRoot,1,list); for(int i = 0;i < list.size();i++){ if(i % 2 != 0){ Collections.reverse(list.get(i)); } } return list;

}
public void depth(TreeNode root,int depth,ArrayList<ArrayList<Integer>> list){
    if(root == null){
        return;
    }
    if(depth > list.size()){
        list.add(new ArrayList<Integer>());
    }
    list.get(depth - 1).add(root.val);
    depth(root.left,depth + 1,list);
    depth(root.right,depth + 1,list);
}

}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务