标签:des style blog http color io strong ar for
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?
算法思路:
思路1:递归版
代码如下:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 List<Integer> res = new ArrayList<Integer>(); 12 public List<Integer> preorderTraversal(TreeNode root) { 13 if(root == null) return res; 14 res.add(root.val); 15 if(root.left != null) preorderTraversal(root.left); 16 if(root.right != null) preorderTraversal(root.right); 17 return res; 18 } 19 }
2. 非递归实现:
借助栈,每一次弹栈处理栈顶元素之后都将右节点、左节点分别压栈,大家画个图就明白了
代码如下:
1 public class Solution { 2 public List<Integer> preorderTraversal(TreeNode root) { 3 List<Integer> res = new ArrayList<Integer>(); 4 if(root == null) return res; 5 Stack<TreeNode> stack = new Stack<TreeNode>(); 6 stack.push(root); 7 while(!stack.isEmpty()){ 8 TreeNode node = stack.pop(); 9 res.add(node.val); 10 if(node.right != null){ 11 stack.push(node.right); 12 } 13 if(node.left != null){ 14 stack.push(node.left); 15 } 16 } 17 return res; 18 } 19 }
[leecode]Binary Tree Preorder Traversal
标签:des style blog http color io strong ar for
原文地址:http://www.cnblogs.com/huntfor/p/3947945.html