39.Binary Tree Inorder Traversal (binary preorder)

Level:

  Medium

Subject description:

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

Analysis of ideas:

  Realization of a binary tree preorder, we can use simple recursive method to achieve, can also be used to implement the stack, use the second approach, we first traverse the left subtree of left child along the root, which in turn will pushed onto the stack, know the child left empty, pop stack node, then record the value of the stack node, if the right child node of the top of the stack is not empty, pushed onto the stack, if it is empty, continues to pop the top element, repeating the above operations, the results can be obtained in order traversal.

Code:

/**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;
    } 
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11074902.html