力扣链接
前序:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/submissions/
中序:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
后序:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
一、分别解释
前序遍历,父节点先遍历,遍历顺序为:父节点-》左节点-》右节点
中序遍历,父节点中间遍历,遍历顺序为:左节点-》父节点-》右节点
后序遍历,父节点后遍历,遍历顺序为:左节点-》右节点-》父节点
二、递归和迭代解决
1.递归
代码如下(示例):
前序:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
preorder(root,result);
return result;
}
public void preorder(TreeNode root, List<Integer> result){
if(root==null){
return;
}
result.add(root.val);
preorder(root.left,result);
preorder(root.right,result);
}
}
中序
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
inorder(root,result);
return result;
}
public void inorder(TreeNode root,List<Integer> result){
if(root==null){
return;
}
inorder(root.left,result);
result.add(root.val);
inorder(root.right,result);
}
}
后序
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
postorder(root,result);
return result;
}
public void postorder(TreeNode root, List<Integer> result){
if(root == null){
return;
}
postorder(root.left,result);
postorder(root.right,result);
result.add(root.val);
}
}
2.迭代(利用栈)
代码如下(示例):
前序:class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while(cur!=null || !stack.isEmpty()){
if(cur!=null){
result.add(cur.val);
stack.push(cur);
cur = cur.left;
}else{
cur = stack.pop();
cur = cur.right;
}
}
return result;
}
中序:class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
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();
result.add(cur.val);
cur = cur.right;
}
}
return result;
}
}
后序:class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> result = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while(cur!=null || !stack.isEmpty()){
if(cur!=null){
result.addFirst(cur.val);
stack.push(cur);
cur = cur.right;
}else{
cur = stack.pop();
cur = cur.left;
}
}
return result;
}
这里中序遍历参考资料:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/solution/dong-hua-yan-shi-94-er-cha-shu-de-zhong-xu-bian-li/
动图满分!!!。
参考知乎资料:https://zhuanlan.zhihu.com/p/81033647
总结
这里结合最后的参考资料不难理解,基本都模板化了!