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

inOrder 二叉树中序遍历

作者: 7ccc099f4608 | 来源:发表于2018-11-11 11:36 被阅读32次

    慢慢练脑子

    1. 来源:

    题: leetcode

    2. 解法:

    2.1 递归

    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            helper(result, root);
            
            return result;
        }
        
        private void helper(List<Integer> result, TreeNode root) {
            
            if(root == null) {
                return;
            }
            
            helper(result, root.left);
            result.add(root.val);
            helper(result, root.right);
            
        }
    }
    

    2.1 非递归

    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            
            List<Integer> inOrderList = new ArrayList<>();
            if(root == null) {
                return inOrderList;
            }
            
            Stack<TreeNode> nodeStack = new Stack<>();
            while(root != null) {
                nodeStack.push(root);
                root = root.left;
            }
            
            while(! nodeStack.isEmpty()) {
                TreeNode curNode = nodeStack.peek();
                inOrderList.add(curNode.val);
                
                if(curNode.right != null) {
                    curNode = curNode.right;
                    while(curNode != null) {
                        
                        nodeStack.push(curNode);
                        curNode = curNode.left;
                        
                    }
                    
                } else {
                    curNode = nodeStack.pop();
                    while(!nodeStack.isEmpty()
                         && nodeStack.peek().right == curNode) {
                        curNode = nodeStack.pop();
                    }
                    
                }
                
            }
            
            return inOrderList;
        }
    }
    

    相关文章

      网友评论

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

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