1. 先序遍历
思路:栈,根节点进栈,然后放右节点,再放左节点,完毕后,依次出栈
代码
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public List<Integer> preorderTraversal(TreeNode root) {
// if(root == null) return null;
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
res.add(node.val);
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
}
return res;
}
2.中序遍历
思路 : 依次从根节点往下放入所有的左叶子节点,直到为null,然后出栈,并打印其右叶子节点
代码
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while(root != null || !stack.isEmpty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
res.add(root.val);
root = root.right;
}
return res;
}
后序遍历
思路:跟前序大致相同,只不过入栈方向相反,因为要确立另一个栈,第一个栈出战的元素要再次放入另一个临时站,最后全部pop出来。
代码
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
Stack<TreeNode> stack2 = new Stack<>();
while(!stack.isEmpty()){
TreeNode node = stack.pop();
stack2.push(node);
if(node.left != null) stack.push(node.left);
if(node.right != null) stack.push(node.right);
}
while(!stack2.isEmpty()){
res.add(stack2.pop().val);
}
return res;
}
广度优先遍历
思路:父节点入队,父节点出队列,先左子节点入队,后右子节点入队。递归遍历
代码:
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null){
return res;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
int count = queue.size();
List<Integer> list = new ArrayList<>();
while(count > 0){
TreeNode tmp = queue.poll();
list.add(tmp.val);
if(tmp.left != null) queue.add(tmp.left);
if(tmp.right != null) queue.add(tmp.right);
count--;
}
res.add(list);
}
return res;
}
深度优先遍历
思路:父节点入栈,父节点出栈,先右子节点入栈,后左子节点入栈。递归遍历
public void Dfs(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
System.out.print(node.val + " ");
if(node.right != null){
stack.push(node.right);
}
if(node.left != null){
stack.push(node.left);
}
}
}