首页 > 其他 > 详细

144. Binary Tree Preorder Traversal

时间:2019-03-28 16:33:39      阅读:125      评论:0      收藏:0      [点我收藏+]

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

Example:

Input: [1,null,2,3]
   1
         2
    /
   3

Output: [1,2,3]

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

 

 

非递归实现二叉树的前序遍历

 

java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public List<Integer> preorderTraversal(TreeNode root) {
12         List<Integer> res = new ArrayList<>() ;
13         Stack<TreeNode> stack = new Stack<>() ;
14         stack.push(root) ;
15         while(!stack.isEmpty()){
16             TreeNode node = stack.pop() ;
17             if (node == null){
18                 continue ;
19             }
20             res.add(node.val) ;
21             stack.push(node.right) ;
22             stack.push(node.left) ;
23         }
24         return res ;
25     }
26 }

 

144. Binary Tree Preorder Traversal

原文:https://www.cnblogs.com/mengchunchen/p/10615894.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!