Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit4d02acd

Browse files
author
applewjg
committed
Binary Tree Inorder Traversal
Change-Id: I2b09a1c587045b693f3aba8bc5acf796c26d98f4
1 parent2f314fe commit4d02acd

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

‎BinaryTreeInorderTraversal.java

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 20, 2014
4+
Problem: Binary Tree Inorder Traversal
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/binary-tree-inorder-traversal/
7+
Notes:
8+
Given a binary tree, return the inorder traversal of its nodes' values.
9+
For example:
10+
Given binary tree {1,#,2,3},
11+
1
12+
\
13+
2
14+
/
15+
3
16+
return [1,3,2].
17+
Note: Recursive solution is trivial, could you do it iteratively?
18+
19+
Solution: 1. Recursive solution. Time: O(n), Space: O(n).
20+
2. Iterative way (stack). Time: O(n), Space: O(n).
21+
3. Threaded tree (Morris). Time: O(n), Space: O(1).
22+
*/
23+
24+
/**
25+
* Definition for binary tree
26+
* public class TreeNode {
27+
* int val;
28+
* TreeNode left;
29+
* TreeNode right;
30+
* TreeNode(int x) { val = x; }
31+
* }
32+
*/
33+
publicclassSolution {
34+
publicList<Integer>inorderTraversal_1(TreeNoderoot) {
35+
List<Integer>res =newArrayList<Integer>();
36+
if (root ==null)returnres;
37+
inorder(root,res);
38+
returnres;
39+
}
40+
publicvoidinorder(TreeNoderoot,List<Integer>res) {
41+
if (root ==null)return;
42+
inorder(root.left,res);
43+
res.add(root.val);
44+
inorder(root.right,res);
45+
}
46+
publicList<Integer>inorderTraversal_2(TreeNoderoot) {
47+
List<Integer>res =newArrayList<Integer>();
48+
Stack<TreeNode>stk =newStack<TreeNode>();
49+
TreeNodecur =root;
50+
while (stk.isEmpty() ==false ||cur !=null) {
51+
if (cur !=null) {
52+
stk.push(cur);
53+
cur =cur.left;
54+
}else {
55+
cur =stk.pop();
56+
res.add(cur.val);
57+
cur =cur.right;
58+
}
59+
}
60+
returnres;
61+
}
62+
publicList<Integer>inorderTraversal(TreeNoderoot) {
63+
List<Integer>res =newArrayList<Integer>();
64+
TreeNodecur =root;
65+
while (cur !=null) {
66+
if (cur.left ==null) {
67+
res.add(cur.val);
68+
cur =cur.right;
69+
}else {
70+
TreeNodenode =cur.left;
71+
while (node.right !=null &&node.right !=cur)
72+
node =node.right;
73+
if (node.right ==null) {
74+
node.right =cur;
75+
cur =cur.left;
76+
}else {
77+
res.add(cur.val);
78+
node.right =null;
79+
cur =cur.right;
80+
}
81+
}
82+
}
83+
returnres;
84+
}
85+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp