Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes‘ values.
Example
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,3,2]
.
SOLUTION 1:
递归方法,具体代码可以参照preorder traversal,这里就不赘述了。
SOLUTION 2:
分治法,Divide & conquer,其实这个代码也可以参照preorder traversal,只贴个代码吧:
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> result = new ArrayList<Integer>(); if (root == null){ return result; } ArrayList<Integer> left = inorderTraversal(root.left); ArrayList<Integer> right = inorderTraversal(root.right); // 差别就是result里面先加入了left,再root,再right result.addAll(left); result.add(root.val); result.addAll(right); return result; } }
SOLUTION 3:
非递归,non-recursion,首先我们模拟一下这个中序遍历过程,就是用一个cur指针从root 一路走到最左下角叶节点(DFS),然后逐层回退,访问回退节点的右节点,当走到右节点的叶节点时再继续回退找下一个右节点。
由于stack.pop()之后就找不到这个树上的点的位置了,所以要用一个点纪录一下,这个根节点,然后继续访问以这个记录点为根的右节点。代码如下:
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> result = new ArrayList<Integer>(); if (root == null){ return result; } Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode cur = root; while (cur != null || !stack.empty()){ while (cur != null){ stack.push(cur); cur = cur.left; } cur = stack.peek(); stack.pop(); result.add(cur.val); cur = cur.right; } return result; } }
时间: 2024-10-23 02:22:15