LeetCode(144):Binary Tree Preorder Traversal
发布日期:2021-05-15 10:07:09 浏览次数:12 分类:博客文章

本文共 1238 字,大约阅读时间需要 4 分钟。

Given a binary tree, return the preorder traversal of its nodes' values.

For example:

Given binary tree {1,#,2,3},

1    \     2    /   3

 

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

 

非递归法(用栈来还原递归过程):

public class Solution {      static  List
res = new ArrayList<>(); static Stack
stack = new Stack<>(); public static List
preorderTraversal_inStack(TreeNode root) { if(root == null) return new ArrayList
(); stack.push(root); while(!stack.isEmpty()){ TreeNode tr = stack.pop(); res.add(tr.val); if(tr.right!=null){ stack.push(tr.right); } if(tr.left!=null){ stack.push(tr.left); } } return res; }

 

递归法:

public static List
preorderTraversal(TreeNode root) { if(root==null) return new ArrayList
(); res.add(root.val); while(root.right!=null||root.left!=null){ preorderTraversal(root.right); preorderTraversal(root.left); } return res; }

 

上一篇:Leetcode(93): Restore IP Addresses
下一篇:LeetCode (238):Product of Array Except Self

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年05月03日 04时16分45秒