144.Binary Tree Preorder Traversal---二叉樹先序、中序非遞歸遍歷

題目連接數組

題目大意:返回二叉樹的先序遍歷list。中序見94,後序見145。ide

法一:普通遞歸遍歷,只是這裏多了一個list數組,因此分紅了兩個函數。代碼以下(耗時1ms):函數

 1     public List<Integer> preorderTraversal(TreeNode root) {
 2         List<Integer> list = new ArrayList<Integer>();
 3         list = dfs(root, list);
 4         return list;
 5     }
 6     public static List<Integer> dfs(TreeNode root, List<Integer> list) {
 7         if(root == null) {
 8             return list;
 9         }
10         else {
11             list.add(root.val);
12             list = dfs(root.left, list);
13             list = dfs(root.right, list);
14             return list;
15         }
16     }
View Code

法二(借鑑):先序非遞歸。代碼以下(耗時1ms):spa

 1     public List<Integer> preorderTraversal(TreeNode root) {
 2         Stack<TreeNode> stack = new Stack<TreeNode>();
 3         TreeNode tmp = root;
 4         List<Integer> list = new ArrayList<Integer>();
 5         while(tmp != null || !stack.isEmpty()) {
 6             //將全部左孩子壓棧,直到沒有左孩子,而且因爲是先序遍歷,因此在壓左孩子的時候就放入結果list中
 7             while(tmp != null) {
 8                 list.add(tmp.val);
 9                 stack.push(tmp);
10                 tmp = tmp.left;
11             }
12             //若是左孩子壓完了,就訪問右孩子
13             if(!stack.isEmpty()) {
14                 tmp = stack.pop();
15                 tmp = tmp.right;
16             }
17         }
18         return list;
19     }
View Code

 

中序非遞歸3d

 1     public List<Integer> inorderTraversal(TreeNode root) {
 2         List<Integer> list = new ArrayList<Integer>();
 3         Stack<TreeNode> stack = new Stack<TreeNode>();
 4         TreeNode tmp = root;
 5         while(tmp != null || !stack.isEmpty()) {
 6             while(tmp != null) {
 7                 stack.push(tmp);
 8                 tmp = tmp.left;
 9             }
10             //與先序不一樣的是,在彈出時放入結果list
11             if(!stack.isEmpty()) {
12                 tmp = stack.pop();
13                 list.add(tmp.val);
14                 tmp = tmp.right;
15             }
16         }
17         return list;
18     }
View Code
相關文章
相關標籤/搜索