二叉树节点的定义方法
public 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;
}
}
前序遍历
对应力扣题目144. 二叉树的前序遍历 - 力扣(LeetCode)
1.递归法
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
traversal(root,res);
return res;
}
public void traversal(TreeNode root,List<Integer> list){
if(root==null)return;
list.add(root.val);
traversal(root.left,list);
traversal(root.right,list);
}
}
2.迭代法
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<Integer>();
if(root==null) return res;
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur= stack.pop();
res.add(cur.val);
if(cur.right!=null){
stack.push(cur.right);
}
if(cur.left!=null){
stack.push(cur.left);
}
}
return res;
}
}
后序遍历
对应力扣题目 145. 二叉树的后序遍历 - 力扣(LeetCode)
1.递归法
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
postorder(root,res);
return res;
}
public void postorder(TreeNode root,List<Integer> list){
if(root==null) return;
postorder(root.left,list);
postorder(root.right,list);
list.add(root.val);
}
}
2.迭代法
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
if(root==null)return res;
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur=stack.pop();
res.add(cur.val);
if(cur.left!=null){
stack.push(cur.left);
}
if(cur.right!=null){
stack.push(cur.right);
}
}
Collections.reverse(res);
return res;
}
}
解释:从前序遍历转换而来,前序加入栈的顺序为中右左,输出顺序为中左右。
后序加入栈的顺序为中左右,输出顺序为中右左。将列表反转则为左右中。
中序遍历
对应力扣题目94. 二叉树的中序遍历 - 力扣(LeetCode)
1.递归法
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<Integer>();
inorder(root,res);
return res;
}
public void inorder(TreeNode root,List<Integer> list){
if(root==null)return;
inorder(root.left,list);
list.add(root.val);
inorder(root.right,list);
}
}
2.迭代法
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
if(root==null)return res;
Stack<TreeNode> stack=new Stack<>();
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;
}
}
解释: 与前序和后序不同,因为中序遍历的顺序和查找顺序不一样。此时栈用来记录已经查找的节点。思路为先查找最左边的节点,并将路径添加到栈中,查找到后从栈中取出根节点,之后查找右节点。
若要将上面三种迭代法统一可查看代码随想录 (programmercarl.com)