标签:
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]
.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { List<Integer> res; public List<Integer> preorderTraversal(TreeNode root) { /* //借助栈数据结构 List<Integer> res=new ArrayList<Integer>(); if(root==null) return res; Stack<TreeNode> stack=new Stack<TreeNode>(); TreeNode node=root; while(node!=null||!stack.isEmpty()){//条件 while(node!=null){ res.add(node.val);///先序 stack.push(node); node=node.left; } node=stack.pop(); //res.add(node.val);中序 node=node.right; } return res;*/ res=new ArrayList<Integer>(); preorder(root); return res; } public void preorder(TreeNode node){ if(node==null) return; res.add(node.val); preorder(node.left); preorder(node.right); } }
[leedcode 144] Binary Tree Preorder Traversal
标签:
原文地址:http://www.cnblogs.com/qiaomu/p/4678962.html