今日内容:
● 二叉树理论基础
● 递归遍历
● 迭代遍历
● 统一迭代
144. 二叉树的前序遍历
先是递归写法
class Solution {
List<Integer> res;
public List<Integer> preorderTraversal(TreeNode root) {
res =new ArrayList<>();
recur(root);
return res;
}
private void recur(TreeNode root) {
if(root == null){
return;
}
res.add(root.val);
recur(root.left);
recur(root.right);
}
}
然后是迭代写法
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> res = new ArrayList<>();
if(root == null)return res;
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;
}
}
94. 二叉树的中序遍历
先是递归写法
class Solution {
private List<Integer> res;
public List<Integer> inorderTraversal(TreeNode root) {
res = new ArrayList<Integer>();
find(root);
return res;
}
private void find(TreeNode root) {
if(root == null) {
return;
}
find(root.left);
res.add(root.val);
find(root.right);
}
}
然后是迭代写法 中序遍历的迭代和其他两种不一样
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> res = new ArrayList<>();
if(root == null)return res;
TreeNode cur = root;
while(cur != null || !stack.isEmpty()) {
if(cur != null) {
stack.push(cur);
cur = cur.left;
} else {
cur = stack.pop();
res.add(cur.val);
cur = cur.right;
}
}
return res;
}
}
145. 二叉树的后序遍历
先是递归写法
class Solution {
List<Integer> res;
public List<Integer> postorderTraversal(TreeNode root) {
res =new ArrayList<>();
recur(root);
return res;
}
private void recur(TreeNode root) {
if(root == null){
return;
}
recur(root.left);
recur(root.right);
res.add(root.val);
}
}
然后是迭代写法
中右左入栈,然后再反转
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> res = new ArrayList<>();
if(root == null)return res;
stack.push(root);
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
res.add(node.val);
if(node.left != null) {
stack.push(node.left);
}
if(node.right != null) {
stack.push(node.right);
}
}
Collections.reverse(res);
return res;
}
}