首页 > 代码库 > lintcode 66.67.68 二叉树遍历(前序、中序、后序)
lintcode 66.67.68 二叉树遍历(前序、中序、后序)
AC代码:
/** * 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) { ArrayList<Integer> res=new ArrayList<>(); if(root==null) return res; res.add(root.val); res.addAll(preorderTraversal(root.left)); res.addAll(preorderTraversal(root.right)); return res; } }
题目来源: http://www.lintcode.com/zh-cn/problem/binary-tree-preorder-traversal/
AC代码:
/** * 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: Inorder in ArrayList which contains node values. */ public ArrayList<Integer> inorderTraversal(TreeNode root) { ArrayList<Integer> res=new ArrayList<>(); if(root==null) return res; res.addAll(inorderTraversal(root.left)); res.add(root.val); res.addAll(inorderTraversal(root.right)); return res; } }
题目来源: http://www.lintcode.com/zh-cn/problem/binary-tree-inorder-traversal/#
AC代码:
/** * 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: Postorder in ArrayList which contains node values. */ public ArrayList<Integer> postorderTraversal(TreeNode root) { ArrayList<Integer> res=new ArrayList<>(); if(root==null) return res; res.addAll(postorderTraversal(root.left)); res.addAll(postorderTraversal(root.right)); res.add(root.val); return res; } }
题目来源: http://www.lintcode.com/zh-cn/problem/binary-tree-postorder-traversal/#
lintcode 66.67.68 二叉树遍历(前序、中序、后序)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。