首页 > 代码库 > 数据结构复习--binary tree pre-order / post-order / in-order traversal
数据结构复习--binary tree pre-order / post-order / in-order traversal
简单递归实现:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
preorderTraversal(result, root);
return result;
}
public void preorderTraversal(List<Integer> result, TreeNode root){
if(root==null)
return;
result.add(root.val);
preorderTraversal(result, root.left);
preorderTraversal(result, root.right);
}
public void postorderTraversal(List<Integer> result, TreeNode root){
if(root==null)
return;
postorderTraversal(result, root.left);
postorderTraversal(result, root.right);
result.add(root.val);
}
public void inorderTraversal(List<Integer> result, TreeNode root){
if(root==null)
return;
inorderTraversal(result, root.left);
result.add(root.val);
inorderTraversal(result, root.right);
}
}
数据结构复习--binary tree pre-order / post-order / in-order traversal