用stack实现二叉树的中序遍历

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lynn_Kun/article/details/76886751

二叉树的中序遍历

样例

给出二叉树 {1,#,2,3},

   1
    \
     2
    /
   3

返回 [1,3,2].

/**
 * 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;
 *     }
 * }
 */
 
import java.util.ArrayList;
import java.util.Stack;
 
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> result=new ArrayList<Integer>();
        Stack<TreeNode> stack=new Stack<TreeNode>();
        TreeNode curt=root;
        while(curt!=null||!stack.empty()){
            while(curt!=null){
                stack.add(curt);
                curt=curt.left;
            }
            curt=stack.peek();
            result.add(curt.val);
            stack.pop();
            curt=curt.right;
        }
        return result;
    }
}


阅读更多
换一批

没有更多推荐了,返回首页