39.Binary Tree Inorder Traversal(二叉树中序遍历)

Level:

  Medium

题目描述:

Given a binary tree, return the inorder traversal of its nodes' values.

思路分析:

  实现一棵二叉树的中序遍历,我们可以用简单的递归方法去实现,也可以使用栈去实现,使用第二种方式时,我们沿着根节点先遍历左子树的左孩子,将它们依次压入栈,知道左孩子为空,弹出栈顶节点,这时记录栈顶节点的值,如果栈顶节点的右孩子不为空,压入栈,如果为空,则栈顶元素继续弹出,重复上述操作,就能获得中序遍历的结果。

代码:

/**public class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int x){
        val=x;
    }
}*/
public class Solution{
    public List<Integer> inorderTraversal(TreeNode root){
        List<Integer>res=new ArrayList<>();
        Stack<TreeNode>s=new Stack<>();
        if(root==null)
            return res;
        TreeNode pNode=root;
        while(pNode!=null||!s.isEmpty()){
            if(pNode!=null){
                s.push(pNode);
                pNode=pNode.left;
            }else{
                TreeNode Node=s.pop();
                res.add(Node.val);
                pNode=Node.right;
            }
        }
        return res;
    } 
}
原文地址:https://www.cnblogs.com/yjxyy/p/11074902.html