标签:
题目:
给出一棵二叉树,返回其节点值的前序遍历。
给出一棵二叉树 {1,#,2,3}
,
1
2
/
3
返回 [1,2,3]
.
你能使用非递归实现么?
解题:
通过递归实现,根节点->左节点->右节点
Java程序:
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: Preorder in ArrayList which contains node values. */ public ArrayList<Integer> preorderTraversal(TreeNode root) { // write your code here ArrayList<Integer> res = new ArrayList<Integer>(); res = preTurn(res,root); return res; } public ArrayList<Integer> preTurn(ArrayList<Integer> res ,TreeNode root){ if(root==null) return res; if(root!=null){ res.add(root.val); if(root.left!=null){ res= preTurn(res,root.left); } if(root.right!=null){ res = preTurn(res,root.right); } } return res; } }
总耗时: 1094 ms
Python程序:
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: Preorder in ArrayList which contains node values. """ def preorderTraversal(self, root): # write your code here res = [] res = self.preorderTurn(res,root) return res def preorderTurn(self,res,root): if root==None: return res if root!=None: res.append(root.val) if root.left!=None: res = self.preorderTurn(res,root.left) if root.right!=None: res = self.preorderTurn(res,root.right) return res;
总耗时: 335 ms
非递归程序,直接来源
Java程序:
public class Solution { /** * @param root: The root of binary tree. * @return: Preorder in ArrayList which contains node values. */ public ArrayList<Integer> preorderTraversal(TreeNode root) { // write your code here ArrayList<TreeNode> p = new ArrayList<TreeNode>(); ArrayList<Integer> res = new ArrayList<Integer>(); while (root != null || p.size() != 0){ res.add(root.val); if (root.right != null) p.add(root.right); root = root.left; if (root == null && p.size() != 0){ root = p.get(p.size()-1); p.remove(p.size()-1); } } return res; } }
总耗时: 1473 ms
Python程序:
class Solution: """ @param root: The root of binary tree. @return: Preorder in ArrayList which contains node values. """ def preorderTraversal(self, root): # write your code here res = [] p = [root] while root is not None or len(p) != 1: res.append(root.val) if root.right is not None: p.append(root.right) root = root.left if root == None and len(p) != 1: root = p[len(p) - 1] del p[len(p) - 1] return res
总耗时: 230 ms
lintcode 容易题:Binary Tree Preorder Traversal 二叉树的前序遍历
标签:
原文地址:http://www.cnblogs.com/theskulls/p/4866237.html