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

二叉树的中序遍历

作者: 二进制的二哈 | 来源:发表于2019-12-19 23:15 被阅读0次

    简书来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal

    给定一个二叉树,返回它的中序 遍历。

    示例:

    输入: [1,null,2,3]
       1
        \
         2
        /
       3
    
    输出: [1,3,2]
    

    递归解法:

    /**
     * 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> ans = new ArrayList<>();
            inorder(ans,root);
            return ans;
        }
    
         private void inorder(List<Integer> ans,TreeNode root){
            if (root == null)
                return;
            inorder(ans,root.left);
            ans.add(root.val);
            inorder(ans,root.right);
        }
    }
    

    迭代解法:

    /**
     * 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> ans = new ArrayList<>();
            Stack<TreeNode> stack = new Stack<>();
            addLeft(stack,root);
            while(!stack.empty()){
                TreeNode pop = stack.pop();
                ans.add(pop.val);
                if (pop.right != null){
                    addLeft(stack,pop.right);
                }
            }
            return ans;
        }
    
    
        private void addLeft(Stack<TreeNode> stack,TreeNode root){
            while(root != null){
                stack.push(root);
                root = root.left;
            }
        }
    }
    

    相关文章

      网友评论

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

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