144. 二叉树的前序遍历(正:1)

题目详情见:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/

/*
方法一:递归法
*/
class Solution {
     public List<Integer> preorderTraversal(TreeNode root) {
       List<Integer> list = new ArrayList<>();
       PTB(list, root);
       return list;
    }
    public void PTB(List<Integer> list, TreeNode root) {
        if (root != null) {
            list.add(root.val);
            PTB(list, root.left);
            PTB(list, root.right);
        }
    }
}
/*
方法二:栈的方法
*/
public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
       List<Integer> res = new ArrayList<>();
       if (root == null) return res;

       Deque<TreeNode> stack = new LinkedList<>();
       stack.addLast(root);
       TreeNode point;

       while (stack.isEmpty()) {
           point = stack.pollLast();
           res.add(point.val);
           if (point.right != null)
               stack.addLast(point.right);
           if (point.left != null)
               stack.addLast(point.left);
       }
       return res;
    }
}
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页