算法:树的遍历
1.1 解法一:递归求解
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
inOrder(root, result);
return result;
}
private void inOrder(TreeNode root, List<Integer> list) {
if (root==null) return;
inOrder(root.left, list);
list.add(root.val);
inOrder(root.right, list);
}
1.2 解法二:自己维护一个栈
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Deque<TreeNode> deque = new LinkedList<>();
while (root!=null || !deque.isEmpty()) {
while (root!=null) {
deque.push(root);
root = root.left;
}
root = deque.pop();
result.add(root.val);
root = root.right;
}
return result;
}
2.1 解法一:递归求解
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
preorder(root, result);
return result;
}
private void preorder(TreeNode node, List<Integer> list) {
if (node==null) return;
list.add(node.val);
preorder(node.left, list);
preorder(node.right, list);
}
2.2 解法二:自己维护一个栈
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Deque<TreeNode> deque = new LinkedList<>();
while (root!=null || !deque.isEmpty()) {
if (root!=null) {
result.add(root.val);
if (root.right!=null) deque.push(root.right);
root = root.left;
}else {
root = deque.pop();
}
}
return result;
}
解法一:递归求解
public List<Integer> postorder(Node root) {
List<Integer> result = new ArrayList<>();
postorder(root, result);
return result;
}
private void postorder(Node node, List<Integer> list) {
if (node==null) return;
if (node.children!=null && node.children.size()>0) {
for (Node childNode: node.children) {
postorder(childNode, list);
}
}
list.add(node.val);
}
解法一:递归求解
public List<Integer> preorder(Node root) {
List<Integer> result = new ArrayList<>();
preorder(root, result);
return result;
}
private void preorder(Node root, List<Integer> result) {
if (root==null) return;
result.add(root.val);
if (root.children!=null && root.children.size()>0) {
for (Node node: root.children) {
preorder(node, result);
}
}
}
解法一:BFS,维护一个栈
public List<List<Integer>> levelOrder(Node root) {
Deque<Node> deque = new LinkedList<>();
List<List<Integer>> result = new ArrayList<>();
if (root!=null) deque.push(root);
while (!deque.isEmpty()) {
int size = deque.size();
List<Integer> list = new ArrayList<>(size);
for (int i=0; i<size; i++) {
Node node = deque.pop();
list.add(node.val);
if (node.children!=null && node.children.size()>0) {
for (Node childNode : node.children) {
deque.addLast(childNode);
}
}
}
result.add(list);
}
return result;
}