lintcode,二叉树的前序遍历
2016-12-15 19:56
429 查看
给出一棵二叉树,返回其节点值的前序遍历。
解题思路:递归和非递归,三种遍历类似。
一刷ac
递归
非递归
解题思路:递归和非递归,三种遍历类似。
一刷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<Integer>(); if(root == null) return res; res.add(root.val); if(root.left != null) res.addAll(preorderTraversal(root.left)); if(root.right != null) res.addAll(preorderTraversal(root.right)); return res; } }
非递归
/** * 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<Integer>(); if(root == null) return res; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while(!stack.empty()){ TreeNode node = stack.pop(); res.add(node.val); if(node.right != null) stack.push(node.right); if(node.left != null) stack.push(node.left); } return res; } }
相关文章推荐
- 二叉树的前序遍历-LintCode
- lintcode--二叉树的前序遍历
- Lintcode 66 二叉树的前序遍历
- LintCode -- 二叉树的前序遍历
- [LintCode] 二叉树的前序遍历
- LintCode 66 二叉树的前序遍历
- [LintCode]66.二叉树的前序遍历
- LintCode 二叉树的前序遍历
- LintCode | 66. 二叉树的前序遍历
- lintcode:二叉树的前序遍历
- LintCode_066_二叉树的前序遍历
- LintCode_066_二叉树的前序遍历
- lintcode 容易题:Binary Tree Preorder Traversal 二叉树的前序遍历
- 非递归前序遍历二叉树-代码实例讲解
- 【LintCode-69】二叉树的层次遍历(Java实现)
- LintCode 二叉树的层次遍历 II
- 【遍历二叉树】01二叉树的前序遍历【Binary Tree Preorder Traversal】
- 二叉树的前序遍历,中序遍历,后序遍历以及相互之间的求法
- 二叉树的前序遍历,中序遍历和后序遍历(c#)
- 前序和中序重建二叉树, 树的前序递归,中序递归,后序递归遍历和前序非递归,中序非递归,后序非递归遍历