二叉树的中序遍历
题目
给出一棵二叉树,返回其中序遍历
样例
给出二叉树 {1,#,2,3},
1
\
2
/
3
返回 [1,3,2].题解
1.递归法
/**
* 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: Inorder in ArrayList which contains node values.
*/
private ArrayList<Integer> result = new ArrayList<Integer>();
public ArrayList<Integer> inorderTraversal(TreeNode root) {
if (root == null)
{
return result;
}
inorderTraversal(root.left);
result.add(root.val);
inorderTraversal(root.right);
return result;
}
}
2.非递归法
中序遍历的规则是对于任一结点,优先访问其左子节点,而左子节点又可以看做根结点,然后继续访问其左子节点,直到左子节点为空为止,然后以同样的规则访问其右子节点。
遍历规则:
1.对于任一结点P,若左子节点不为null,则将P入栈并将赋值为P的左子节点。
2.对于任一结点P,若其左子节点为null,则将P赋值为取栈顶节点后出栈,记录该结点后将P赋值为P的右子节点,直到P和栈都为null为止。
/**
* 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: 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 p = root;
while (p!=null || !stack.empty())
{
while (p!=null)
{
stack.push(p);
p=p.left;
}
if (!stack.empty())
{
p = stack.peek();
result.add(p.val);
stack.pop();
p = p.right;
}
}
return result;
}
}
Last Update 2016.8.29