144. 二叉树的前序遍历

给定一个二叉树,返回它的 前序 遍历。
/**
 * 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;
 *     }
 * }
 */
//1.递归
class Solution {
    List<Integer> res = new ArrayList<>();
    public List<Integer> preorderTraversal(TreeNode root) {
        preorder(root);
        return res;
    }
    public void preorder(TreeNode node){
        if(node==null)
            return ;
        res.add(node.val);
        preorder(node.left);
        preorder(node.right);
    }
}
//2.迭代
class Solution {  
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        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;
    }
}

上一篇:python基础学习与编程练习笔记(6)——自动轨迹绘制,词云制作


下一篇:第 15 章 垃圾回收相关算法