这个题跟I是一模一样的,我偷懒了,我直接存的时候给他逆序存了一下。
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (root == null) return result;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
int currentElement = 1;
while (q.size() != 0) {
ArrayList<Integer> currentLevel = new ArrayList<Integer>();
int nextElement = 0;
for (int i = 0; i < currentElement; i++){
TreeNode curr = q.poll();
currentLevel.add(curr.val);
if (curr.left != null) {
q.add(curr.left);
nextElement++;
}
if (curr.right != null) {
q.add(curr.right);
nextElement++;
}
}
result.add(0,currentLevel);
currentElement = nextElement;
}
return result;
}
check this solution. It seems much easier than the previous one.
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) return result;
List<TreeNode> nodeList = new ArrayList<TreeNode>();
List<Integer> valueList = new ArrayList<Integer>();
nodeList.add(root);
valueList.add(root.val);
result.add(valueList);
while (nodeList.size() > 0) {
List<TreeNode> tempNodeList = new ArrayList<TreeNode>();
List<Integer> tempValueList = new ArrayList<Integer>();
for (int i = 0; i < nodeList.size(); i++) {
TreeNode currNode = nodeList.get(i);
if (currNode.left != null) {
tempNodeList.add(currNode.left);
tempValueList.add(currNode.left.val);
}
if (currNode.right != null) {
tempNodeList.add(currNode.right);
tempValueList.add(currNode.right.val);
}
}
if (tempValueList.size() > 0) {
result.add(0, tempValueList);
}
nodeList = tempNodeList;
}
return result;
}
No comments:
Post a Comment