首页 > 代码库 > [Leetcode] Binary Tree Inorder Traversal

[Leetcode] Binary Tree Inorder Traversal

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

For example:
Given binary tree {1,#,2,3},

   1         2    /   3

 

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

 

Solution:

1. 非递归

 1 /** 2  * Definition for binary tree 3  * public class TreeNode { 4  *     int val; 5  *     TreeNode left; 6  *     TreeNode right; 7  *     TreeNode(int x) { val = x; } 8  * } 9  */10 public class Solution {11     public List<Integer> inorderTraversal(TreeNode root) {12         List<Integer> result=new ArrayList<Integer>();13         if(root==null)14             return result;15         Stack<TreeNode> s=new Stack<TreeNode>();16         s.add(root);17         TreeNode p=root.left;18         while(!s.isEmpty()){19             while(p!=null){20                 s.add(p);21                 p=p.left;22             }23             TreeNode n=s.pop();24             result.add(n.val);25             p=n.right;26             if(p!=null){27                 s.add(p);28                 p=p.left;29             }30         }31         32         return result;33     }34 }

 

 1 /** 2  * Definition for binary tree 3  * public class TreeNode { 4  *     int val; 5  *     TreeNode left; 6  *     TreeNode right; 7  *     TreeNode(int x) { val = x; } 8  * } 9  */10 public class Solution {11     12     ArrayList<Integer> result = new ArrayList<Integer>();13     14     public ArrayList<Integer> inorderTraversal(TreeNode root) {15         16 17     Stack<TreeNode> stack = new Stack<TreeNode>();18         while (root != null || !stack.empty()) {19             while (root != null) {20                 stack.push(root);21                 root = root.left;22             }23             if (stack.size() > 0) {24                 root = stack.pop();25                 result.add(root.val);26                 root = root.right;27             }28         }29 30         return result;31         32     }33 }

 

2. 递归

 1 /** 2  * Definition for binary tree 3  * public class TreeNode { 4  *     int val; 5  *     TreeNode left; 6  *     TreeNode right; 7  *     TreeNode(int x) { val = x; } 8  * } 9  */10 public class Solution {11     public List<Integer> inorderTraversal(TreeNode root) {12         List<Integer> result=new ArrayList<Integer>();    13         myInorderTraversal(root,result);  14         return result;15     }16 17     private void myInorderTraversal(TreeNode root, List<Integer> result) {18         // TODO Auto-generated method stub19         if(root!=null){20             myInorderTraversal(root.left, result);21             result.add(root.val);22             myInorderTraversal(root.right, result);23         }24     }25 }

 

[Leetcode] Binary Tree Inorder Traversal