美文网首页
94.二叉树的中序遍历

94.二叉树的中序遍历

作者: 皮蛋豆腐酱油 | 来源:发表于2019-05-23 11:20 被阅读0次
    //递归
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        List<Integer> list = new ArrayList<Integer>();
        public List<Integer> inorderTraversal(TreeNode root) {
            if(root!=null) {
                inorderTraversal(root.left);
                list.add(root.val);
                inorderTraversal(root.right);
            }
            return list;
        }
    }
    
    //非递归
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<Integer>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            if(root == null) return list;
            TreeNode p = root;
            while(p != null) {
                stack.push(p);
                p = p.left;
            }
            while(!stack.isEmpty()) {
                TreeNode q = stack.pop();
                list.add(q.val);
                TreeNode k = q.right;               
                while(k != null) {
                    stack.push(k);
                    k = k.left;
                }
                
            }
            return list;
                        
        }
    }
    

    相关文章

      网友评论

          本文标题:94.二叉树的中序遍历

          本文链接:https://www.haomeiwen.com/subject/azxvzqtx.html