Problem
Given two DOM trees with the same structure, and one node in tree1, try to find its symmetric node in tree2
Solution 1
If we are not so familiar with DOM API, we might forget there is an attribute for each DOM element: parentNode
. Then we might just traverse both trees at the same time, when we encounter the node in tree1, the node in tree2 is what we want.
1 | function getSymmetricNode(target, root1, root2){ |
- Time Complexity: O(b^d) [d: depth, b: branches], which is BAD!
Solution 2 [Improved ]
Actually there is an convenient attribute we could utilize, that is parentNode
- First, we could go up to find that path from root1 to target
- The path is consist of indices of node on that path
- Using that path of indices, we could go downwards from root2 to find the desired node
1 | let getSymmetricNode = (target, root1, root2) => { |
Testing
1 | // Testing |