144.二叉树的前序遍历.md

题目链接

https://leetcode-cn.com/problems/binary-tree-preorder-traversal/submissions/

解法

1.递归
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        helper(root,res);
        return res;
    }
    public void helper(TreeNode node,List<Integer> res){
        if(node == null) return;
        res.add(node.val);
        if(node.left != null) helper(node.left,res);
        if(node.right != null) helper(node.right,res);
    }
}

总结:

这个模板前中后序遍历都可以使用,递归解法相对简单,使用helper方法可以避免重复开辟空间

2.使用栈进行迭代
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        //使用迭代方式进行遍历
        //前序遍历:根节点-->左 -- >右
        
        List<Integer> res = new ArrayList<>();
        if(root == null) return res;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode curr = stack.pop();
            res.add(curr.val);
            if(curr.right != null) stack.push(curr.right);
            if(curr.left != null) stack.push(curr.left);
        }
        return res;
    }
    
}

总结:

迭代方式一定要会,并且前中后序每一个迭代具体的实现都不太一样,注意是先将右子树进栈,这样栈顶元素为左子树。

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://hadoo666.top/archives/144二叉树的前序遍历md