The general line of binary tree algorithm design: clearly a node needs to be done, then the rest of the things thrown framework.
void Traverse (TreeNode root) { // root what to do? In doing this. // Other worry not root, thrown frame Traverse (root.left); Traverse (root.right); }
Here are two simple examples to understand what this line of thought, warm up.
1. How the value of all the nodes in the binary tree plus one?
void plusOne(TreeNode root) { if (root == null) return; root.val += 1; plusOne(root.left); plusOne(root.right); }
2. How to determine whether two binary exactly?
Boolean isSameTree (the root1 the TreeNode, the TreeNode root2) { // are empty, then obviously the same IF (the root1 == null && root2 == null ) return to true ; // a blank, a non-empty, is clearly different IF (= the root1 = null || root2 == null ) return false ; // both non-empty, but not the same nor val IF (root1.val = root2.val)! return false ; // than the ratio of root1 and root2 over return isSameTree (root1.left, root2.left) && isSameTree (root1.right, root2.right); }