二叉树中序遍历(递归+非递归)

来源:互联网 发布:电子音乐制作软件 编辑:程序博客网 时间:2024/06/04 18:31

二叉树中序遍历:左-中-右


树节点

 class TreeNode {public int val;      public TreeNode left, right;      public TreeNode(int val) {          this.val = val;         this.left = this.right = null;   }}

递归实现

/* * 二叉树中序遍历 * 递归实现 */public class InorderTraversal {public ArrayList<Integer> inorderTraversal(TreeNode root){ArrayList<Integer> arr = new ArrayList<Integer>();inorder(arr,root);return arr;}public ArrayList<Integer> inorder(ArrayList<Integer> arr, TreeNode root){if(root == null)return arr;if(root!=null){if(root.left!=null){arr = inorder(arr, root.left);}arr.add(root.val);if(root.right!=null){arr = inorder(arr, root.right);}}return arr;}}


非递归实现

/* * 二叉树中序遍历 * 非递归方式 */public class InorderTraversal1 {public ArrayList<Integer> inorderTraversal(TreeNode root){ArrayList<Integer> arr = new ArrayList<Integer>();ArrayList<TreeNode> p =new ArrayList<TreeNode>();if(root == null){return arr;}while(root!=null || p.size()!=0){while(root!=null){p.add(root);root = root.left;}root = p.get(p.size()-1);arr.add(root.val);p.remove(p.size()-1);root = root.right;}return arr;}}



0 0
原创粉丝点击