代码随想录算法训练营第十三天| 144. 二叉树的前序遍历、94. 二叉树的中序遍历、145. 二叉树的后序遍历

LeetCode 144. 二叉树的前序遍历
题目链接:144. 二叉树的前序遍历 - 力扣(LeetCode)代码随想录算法训练营第十三天| 144. 二叉树的前序遍历、94. 二叉树的中序遍历、145. 二叉树的后序遍历_第1张图片

​思路:

对于二叉树,其前中后遍历均可采用递归遍历与迭代遍历,递归很好理解,函数规定以列表的形式返回节点的值,所以我们规定边界条件,即无节点时返回[],随后讨论左孩子情况与右孩子情况。

#python 前序遍历 递归版本
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root: //注意要返回空列表,因为return部分是空列表相加
            return []
        Left = self.preorderTraversal(root.left)
        Right = self.preorderTraversal(root.right)
        return [root.val] + Left + Right 
#python 前序遍历 迭代版本
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        stack = []
        res = []
        if root:
            stack.append(root)
        while stack:
            node = stack.pop()
            if node != None:
                if node.right: //为什么先放right,再放left? 因为我们用的是栈,前进后出
                    stack.append(node.right)
                if node.left:
                    stack.append(node.left)
                stack.append(node)
                stack.append(None) //为什么要加一个None节点进来?
            else:
                node = stack.pop() //因为用一个空节点来标识该部分结束了
                res.append(node.val)
        return res

#python 如果觉得用栈不习惯反着来,也可以是用deque双端队列来实现,这样逻辑就是正常的从左到右了,这个方法也是迭代法
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        stack = collections.deque()
        res = []
        if root:
            stack.append(root)
        while stack:
            node = stack.pop()
            if node != None:
                stack.appendleft(None) //因为用了deque,所以加入节点的时候就中,左,右,这样添加进去,但是pop还是从右边pop
                stack.appendleft(node)
                if node.left:
                    stack.appendleft(node.left)
                if node.right:
                    stack.appendleft(node.right)
            else:
                node = stack.pop()
                res.append(node.val)
        return res
#java 递归法 前序遍历
/**
 * Definition for a binary tree node.
 * 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;
 *     }
 * }
 */
class Solution {
    public List preorderTraversal(TreeNode root) {
        List res = new ArrayList();
        if(root == null){
            return res;
        }
        List left = preorderTraversal(root.left);
        List right = preorderTraversal(root.right);
        res.add(root.val);
        res.addAll(left); //注意这个地方要用addAll,要把所有元素都放进来,只用add会报错的
        res.addAll(right);
        return res;
    }
}
#java 前序遍历 迭代法
/**
 * Definition for a binary tree node.
 * 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;
 *     }
 * }
 */
class Solution {
    public List preorderTraversal(TreeNode root) {
        List res = new ArrayList<>();
        Stack stack = new Stack<>();
        if(root != null)
            stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            if(node != null){
                if(node.right != null)
                    stack.push(node.right);
                if(node.left != null)
                    stack.push(node.left);
                stack.push(node);
                stack.push(null);
            }
            else{
                node = stack.pop();
                res.add(node.val);
            }
        }
        return res;
    }
}

困难与想法:

对于树来说,只要是用迭代法就要想着使用stack来存每一层的节点了。


LeetCode 94. 二叉树的中序遍历

题目链接:94. 二叉树的中序遍历 - 力扣(LeetCode)

代码随想录算法训练营第十三天| 144. 二叉树的前序遍历、94. 二叉树的中序遍历、145. 二叉树的后序遍历_第2张图片
思路:

同前序遍历,只不过是前中的进入位置要进行修改。

代码:

#python 中序遍历 递归版本
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        Left = self.inorderTraversal(root.left)
        Right = self.inorderTraversal(root.right)
        return Left + [root.val] + Right //root.val放的位置不同
#python 中序遍历 迭代法 stack实现
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        stack = []
        if root:
            stack.append(root)
        while stack:
            node = stack.pop()
            if node != None:
                if node.right:
                    stack.append(node.right)
                stack.append(node)  //注意此时是入栈的顺序是右中左,这样对stackpop时就是先左,再中,实现了中序遍历
                stack.append(None)
                if node.left:
                    stack.append(node.left)
            else:
                node = stack.pop()
                res.append(node.val)
        return res
#java 递归法 中序遍历
/**
 * Definition for a binary tree node.
 * 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;
 *     }
 * }
 */
class Solution {
    public List inorderTraversal(TreeNode root) {
        List res = new ArrayList<>();
        if(root == null){
            return res;
        }
        List left = inorderTraversal(root.left);
        List right = inorderTraversal(root.right);
        res.addAll(left);
        res.add(root.val);
        res.addAll(right);
        return res;
    }
}
#java 中序遍历 迭代法
/**
 * Definition for a binary tree node.
 * 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;
 *     }
 * }
 */
class Solution {
    public List inorderTraversal(TreeNode root) {
        List res = new ArrayList<>();
        Stack stack = new Stack<>();
        if(root != null){
            stack.push(root);
        }
        while(!stack.isEmpty()){
            TreeNode node =stack.pop();
            if(node != null){
                if(node.right != null)
                    stack.push(node.right);
                stack.push(node);
                stack.push(null);
                if(node.left != null)
                    stack.push(node.left);
            }
            else{
                node = stack.pop();
                res.add(node.val);
            }
        }
        return res;
    }
}

困难与想法:

同上


LeetCode 145. 二叉树的后序遍历

题目链接:145. 二叉树的后序遍历 - 力扣(LeetCode)

代码随想录算法训练营第十三天| 144. 二叉树的前序遍历、94. 二叉树的中序遍历、145. 二叉树的后序遍历_第3张图片
思路:

注意判断一下操作符,讨论一下各种情况,

代码:

#python 后序遍历 递归版本
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        Left = self.postorderTraversal(root.left)
        Right = self.postorderTraversal(root.right)
        return Left + Right + [root.val]
#python 后序遍历 递归法
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        stack = []
        res = []
        if root:
            stack.append(root)
        while stack:
            node = stack.pop()
            if node != None:
                stack.append(node)  //先把node放入,在放右,放左,这样先pop出左了
                stack.append(None)
                if node.right:
                    stack.append(node.right)
                if node.left:
                    stack.append(node.left)
            else:
                node = stack.pop()
                res.append(node.val)
        return res
#java 后序遍历 递归法
/**
 * Definition for a binary tree node.
 * 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;
 *     }
 * }
 */
class Solution {
    public List postorderTraversal(TreeNode root) {
        List res = new ArrayList<>();
        if(root == null){
            return res;
        }
        List left = postorderTraversal(root.left);
        List right = postorderTraversal(root.right);
        res.addAll(left);
        res.addAll(right);
        res.add(root.val);
        return res;
    }
}
#java 后序遍历 迭代法
/**
 * Definition for a binary tree node.
 * 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;
 *     }
 * }
 */
class Solution {
    public List postorderTraversal(TreeNode root) {
        List res = new ArrayList<>();
        Stack stack = new Stack<>();
        if(root != null){
            stack.push(root);
        }
        while(!stack.isEmpty()){
            TreeNode node =stack.pop();
            if(node != null){
                stack.push(node);
                stack.push(null);
                if(node.right != null){
                    stack.push(node.right);
                }
                if(node.left != null){
                    stack.push(node.left);
                }
            }
            else{
                node = stack.pop();
                res.add(node.val);
            }
        }
        return res;
    }
}

困难与想法:

同上

你可能感兴趣的:(算法,python,java)