标签:
/* * 94. Binary Tree Inorder Traversal * 2015.11.21 By Mingyang * 跟preorder一样的dfs,不过是每次pop出来的时候记在小本本上,也就是记在list里面 中序遍历迭代解法 * 用栈先把根节点的所有左孩子都添加到栈内, 然后输出栈顶元素,再处理栈顶元素的右子树 */ public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<Integer>(); if (root == null) return list; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode p = root; while (!stack.isEmpty() || p != null) { if (p != null) { stack.push(p); p = p.left; } else { TreeNode t = stack.pop(); list.add(t.val); p = t.right; } } return list; } public List<Integer> inorderTraversal1(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); dfs(root, res); return res; } public void dfs(TreeNode root, List<Integer> res) { if (root == null) return; dfs(root.left, res); res.add(root.val); dfs(root.right, res); }
94. Binary Tree Inorder Traversal
标签:
原文地址:http://www.cnblogs.com/zmyvszk/p/5496823.html