struct Node{
int data;
Node *left, *right;
};
void preOrderPrint(Node *root)
{
print(root->name); //record root
if (root->left != NULL) preOrderPrint(root->left); //traverse left if exists
if (root->right != NULL) preOrderPrint(root->right);//traverse right if exists
}
void inOrderPrint(Node *root)
{
if (root.left != NULL) inOrderPrint(root->left); //traverse left if exists
print(root->name); //record root
if (root.right != NULL) inOrderPrint(root->right); //traverse right if exists
}
void postOrderPrint(Node *root)
{
if (root->left != NULL) postOrderPrint(root->left); //traverse left if exists
if (root->right != NULL) postOrderPrint(root->right);//traverse right if exists
print(root->name); //record root
}
如果给定的二叉树是一个二叉查找树,那么遍历将按排序顺序打印出节点。举个例子,如果你需要找到二叉查找树中的 k 最小元素:
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
res=None
def inorder(node):
if not node:
return
# in bst this is the smallest value
inorder(node.left)
# python determines the scope at creation time of the function
nonlocal k
k-=1
if k==0:
nonlocal res
res=node.val
return
inorder(node.right)
inorder(root)
return res
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def post_order(root):
# leaf node is balanced
if not root:
# we carry the height of each subtree
return [True,0]
# with recursion, we start from bottom, so we do not have repetitive work
left,right=post_order(root.left),post_order(root.right)
# if any of the subtree return false, then we know entire tree is not balanced
balanced=left[0] and right[0] and abs(left[1]-right[1])<=1
# 1+max(left[1],right[1]) is the height of the each subtree. 1 is the root of the subtree
return [balanced,1+max(left[1],right[1])]
return post_order(root)[0]
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
if not preorder or not inorder:
return None
# first element of preorder is root
root=TreeNode(preorder[0])
# mid value in inorder gives us root. left values of root will be the left subtree, right values will be the right subtree
# mid tells us how many elements we want from left subtree and howmany for right subtree
mid = inorder.index(preorder[0])
# we took 1 out of each array. preorder will not include the first, inorder will not include the mid value
root.left=self.buildTree(preorder[1:mid+1],inorder[:mid])
root.right=self.buildTree(preorder[mid+1:],inorder[mid+1:])
return root